vue-router使用方法可参照官方手册:起步 | Vue Router (vuejs.org)
基本demo,实现:
demo代码:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!--1.引入vue和vue-router,注意顺序和版本-->
<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router@3/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
<h1>Hello App!</h1>
<!-- 4.使用router-link生成导航的链接 -->
<router-link to="/login">登录</router-link>
<router-link to="/register">注册</router-link>
<!-- 5.路由占位符 -->
<router-view></router-view>
</div>
<script type="text/javascript">
var Login = {
template:'<div><h2>登录组件</h2></div>'
}
var Register = {
template:'<div><h2>注册组件</h2></div>'
}
//2.创建一个路由对象
const router = new VueRouter({
routes:[
{path:'/login',component:Login},
{path:'/register',component:Register}
]
})
var app = new Vue({
el:'#app',
//3.注册路由对象
router:router,
//可缩写为router
}).$mount('#app')
</script>
</body>
</html>
运行结果:
点击登录和注册,分别显示如下:
实际上,router-link,转化为a标签 :