Vue嵌套路由
实际生活中的应用界面,通常由多层组件构成,同样,URL中各段动态。路径也按某种结构对应嵌套的各层组件。
我们使用children属性来完成。
let routes = [
{
path:'/user',component:User,
children:[
{
path:'userList',
component:UserList
},
{
path:'userAdd',
component:UserAdd
},
]
},
{
path:'/emp',component:Emp
},
{
path:'/',component:Index
},
{
path:'/*',component:NotFount
},
]
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> body{ margin: 0; } .layout{ height: 100vh; display: flex; overflow: hidden; } .nav { width: 200px; background: #ccc; } .container { background: red; flex: auto; } </style> </head> <body> <div id="app"> <div class="layout"> <div class="nav"> <h1>导航菜单</h1> <ul> <li><router-link to="/user">用户管理</router-link></li> <li><router-link to="/emp">员工管理</router-link></li> </ul> </div> <div class="container"> <router-view></router-view> </div> </div> </div> <!-- 用户组件模板 --> <template id="user"> <div> <h1>用户管理组件</h1> <router-link to="/user/userList">用户列表</router-link> <router-link to="/user/userAdd">用户新增</router-link> <hr> <router-view></router-view> </div> </template> <template id="emp"> <div> <h1>员工管理组件</h1> </div> </template> <!-- 员工组件模板 --> <script src="../js/vue.js"></script> <!-- 先引入vue的核心库,再引入router的核心库 --> <script src="../js/vue-router.js"></script> <script> // 1、定义组件 let User = { template:'#user', } let UserAdd = { template:'<div><h1>用户新增组件</h1></div>' } let UserList = { template:'<div><h1>用户查询组件</h1></div>' } let Empedit = { template:'<div><h1>员工修改组件</h1></div>' } let Empdelete = { template:'<div><h1>员工删除组件</h1></div>' } let Emp = { template:'#emp' } let Index = { template:'<div><h1>欢迎使用</h1></div>' } let NotFount = { template:'<div><h1>没有该页面</h1></div>' } let routes = [ { path:'/user',component:User, children:[ { path:'userList', component:UserList }, { path:'userAdd', component:UserAdd }, ] }, { path:'/emp',component:Emp }, { path:'/',component:Index }, { path:'/*',component:NotFount }, ] //3、创建router实例,当引入Vue.router之后,VueRouter就会成为全局函数 let router = new VueRouter({ //配置路由列表,配置项的名称routes routes:routes }) let vm = new Vue({ el : "#app", data : { }, //4、将创建号的rouer实例,绑定给vue实例的router属性 router }) </script> </body> </html>