实际生活中的应用界面,通常由多层嵌套的组件组合而成。同样地,URL 中各段动态路径也按某种结构对应嵌套的各层组件
嵌套路由字面上就是路由中嵌套的一个或多个子路由,我直接把完整的代码贴出来,在代码中做解释,看的比较清楚一点,复制后可直接运行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8"> <script src="http://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> </head> <body> <div id="box"> <p> <router-link to="/home">home</router-link> <router-link to="/news">news</router-link> </p> <router-view></router-view> </div> <template id="home"> <div> <h2>首页</h2> <router-link to="/home/login">登录</router-link> <router-link to="/home/reg">注册</router-link> <router-view></router-view> </div> </template> <template id="news"> <div>新闻</div> </template> <template id="login"> <div>登录界面</div> </template> <template id="reg"> <div>注册界面</div> </template> <script type="text/javascript"> const Home = { template: '#home' }; const News = { template: '#news' }; const Login = { template: '#login' }; const Reg = { template: '#reg' }; const routes = [ { path: '/', redirect: '/home' }, { path: '/home', component: Home, children:[ { path: '/home/login', component: Login}, { path: '/home/reg', component: Reg} ] }, { path: '/news', component: News} ] const router = new VueRouter({ routes }) const app = new Vue({ router }).$mount('#box') </script> </body> </html>
|
要注意,以 / 开头的嵌套路径会被当作根路径,这让你充分的使用嵌套组件而无须设置嵌套的路径,children 配置就是像 routes 配置一样的路由配置数组,所以呢,你可以嵌套多层路由。
以上就是我对Vue嵌套路由的一些理解,有不对的地方欢迎提出