实际生活中的应用界面,通常由多层嵌套的组件组合而成。同样地,URL 中各段动态路径也按某种结构对应嵌套的各层组件,例如:
借助 vue-router
,使用嵌套路由配置,就可以很简单地表达这种关系。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.bootcss.com/vue/2.5.22/vue.min.js"></script> <script src="https://cdn.bootcss.com/vue-router/3.0.2/vue-router.min.js"></script> </head> <body> <div id="app"></div> <script type="text/javascript"> //router-view中包含router-view //路由规则中包含子路由 let Login = { template:`<div> <h3>我是login的内容,下面是子路由的内容</h3> <router-view></router-view> </div>` } let Register = { template: `<div> <h3>我是register的内容,下面是子路由的内容</h3> <router-view></router-view> </div>` } let Student = { template:`<div> <h4>学生登录入口</h4> </div>` } let Teacher = { template:`<div> <h4>教师登录入口</h4> </div>` } let router = new VueRouter({ routes:[{ name:'login', path:"/login", component:Login, children:[{ name:"login.student", path:"student", component:Student },{ name:"login.teacher", path:"teacher", component:Teacher } ] },{ name:'register', path:"/register/:name", component:Register, children:[] }] }) let App = { template:` <div> <router-link :to="{name:'login.student'}">学生</router-link> <router-link :to="{name:'login.teacher'}">教师</router-link> <router-view></router-view> </div>` } new Vue({ el:"#app", template:`<app/>`, components:{ app:App }, router:router }) </script> </body> </html>