18.路由的嵌套
1.在components目录下新建目录User,目录下新建两个组件AddUser.vue和UserList.vue
AddUser.vue
<template> <div> <h2>{{msg}}</h2> </div> </template> <script> export default { name: 'home', data () { return { msg:'增加用户' } }, methods:{ }, components:{ } } </script> <style lang="scss" scoped> </style>
UserList.vue
<template> <div> <h2>{{msg}}</h2> </div> </template> <script> export default { name: 'home', data () { return { msg:'用户列表' } }, methods:{ }, components:{ } } </script> <style lang="scss" scoped> </style>
2.在main.js中引入组件,并且配置嵌套路由
main.js
import Vue from 'vue'; import App from './App.vue'; import VueResource from 'vue-resource'; Vue.use(VueResource) import VueRouter from 'vue-router'; Vue.use(VueRouter) // 1.创建组件,导入组件 import Home from './components/Home.vue'; import News from './components/News.vue'; import vContent from './components/vContent.vue'; import Good from './components/Goods.vue'; import User from './components/User.vue'; import AddUser from './components/User/AddUser.vue'; import UserList from './components/User/UserList.vue'; // 2.配置路由 const routes=[ {path:'/home',component:Home}, {path:'/news',component:News}, {path:'/vcontent/:aid',component:vContent}, //动态路由 {path:'*',redirect:'/home'}, //默认路由跳转到首页 {path:'/goods',component:Good}, { path:'/user', component:User, children:[ {path:'adduser',component:AddUser}, {path:'userlist',component:UserList} ] }, ] //注意,这里是routes,而不是routers // 3.实例化VueRouter const router=new VueRouter({ mode:'history',//hash改为history模式 routes//(缩写)相当于routers:routers }) // 4.挂载 new Vue({ el: '#app', router, render: h => h(App) }) // 5.将<router-view></router-view>放在App.vue里面
3.在User.vue中引入<router-view></router-view>
user.vue
<template> <div> <div class="user"> <div class="left"> <ul> <li><router-link to="/user/adduser">增加用户</router-link></li> <li><router-link to="/user/userlist">用户列表</router-link></li> </ul> </div> <div class="right">内容区域 <router-view></router-view> </div> </div> </div> </template> <script> export default { name: 'home', data () { return { msg:'用户中心' } }, methods:{ }, components:{ } } </script> <style lang="scss" scoped> .user{ display: flex; .left{ width:200px; min-height: 400px; border-right: 1px solid #eee; } .right{ flex: 1; } } </style>