1.引入vue-router
2. router-link 标签 切换锚点值 一定要写to属性,不然报错
3. router-view 标签 切换组件的容器
4.初始化router路由对象
5.配置路径(锚点值与组件的对应关系)
6.在实例上挂载路由
如果有子路由,请往最后看!!!
7.demo:
<!DOCTYPE html>
<html lang="en">
<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>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<!-- 1.引入vue-router -->
<script src="./js/vue-router_3.0.2.js"></script>
</head>
<body>
<div id="app">
<!-- 2. router-link 标签 切换锚点值 一定要写to属性,不然报错-->
<router-link to="/login">login</router-link>
<router-link to="/reg">reg</router-link>
<router-link to="/indexCom">indexCom</router-link>
<!-- 3. router-view 标签 切换组件的容器 -->
<router-view></router-view>
</div>
<script>
let login = {
template: `
<div>
<h3>登录</h3>
<input type="text">
</div>
`
}
let reg = {
template: `
<div>
<h3>注册</h3>
<input type="text">
</div>
`
}
let index = {
template: `
<div>
<h3>首页</h3>
<p>个人信息</p>
<input type="text">
</div>
`
}
// 4.初始化router路由对象
let router = new VueRouter({
// 5.配置路径(锚点值与组件的对应关系)
routes: [{
path: '/login',
component: login
}, {
path: '/reg',
component: reg
}, {
path: '/indexCom',
component: index
}, {
path: '/',
redirect: '/indexCom'
}]
})
const app = new Vue({
el: '#app',
data: {},
// 6.在实例上挂载路由
router: router
})
</script>
</body>
</html>
添加子路由:
最后附赠一个Vue-Router中常见的导航方式:
this.$router.push("hash地址");
this.$router.push("/login");
this.$router.push({ name:'user' , params: {id:123} });
this.$router.push({ path:"/login" });
this.$router.push({ path:"/login",query:{username:"jack"} });
this.$router.go( n );//n为数字,参考history.gothis.$router.go( -1 ); //用法类似于 history.go(-1)