背景:
在大的路由下面有时候需要一些字路由进行切换数据,那么这时候需要使用路由嵌套。
方法:
1、直接在父路由中添加`children`字路由,格式和父路由一样。
let router = new VueRouter({ routes: [{ path: "/", component: index, }, { path: "/our", component: our, children: [{ path: "", component: our_msg }, { path: "msg", component: our_msg }, { path: "setting", component: our_setting }] } ] })
2、在父路由组件中要添加路由出口(<router-view></router-view>),否则无法渲染子组件。
var our = Vue.extend({ template: ` <div> <h1>我们</h1> <ul class="nav nav-tabs"> <li role="presentation" class="active"> <router-link to="/our/msg">消息</router-link> </li> <li role="presentation"> <router-link to="/our/setting">设置</router-link> </li> </ul> <div class="container"> <router-view></router-view> </div> </div> ` })
整体代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"> <title>VueRouter-路由嵌套</title> </head> <body> <div id="app"> <nav class="navbar navbar-default"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Brand</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="active"> <router-link to="/">首页</router-link> </li> <li> <router-link to="/our">我们</router-link> </li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> <div class="container"> <router-view></router-view> </div> </div> <script> var index = Vue.extend({ template: "<h1>首页</h1>" }); var our = Vue.extend({ template: ` <div> <h1>我们</h1> <ul class="nav nav-tabs"> <li role="presentation" class="active"> <router-link to="/our/msg">消息</router-link> </li> <li role="presentation"> <router-link to="/our/setting">设置</router-link> </li> </ul> <div class="container"> <router-view></router-view> </div> </div> ` }) var our_setting = Vue.extend({ template: "<h1>设置</h1>" }) var our_msg = Vue.extend({ template: "<h1>消息</h1>" }) let router = new VueRouter({ routes: [{ path: "/", component: index, }, { path: "/our", component: our, children: [{ path: "", component: our_msg }, { path: "msg", component: our_msg }, { path: "setting", component: our_setting }] } ] }) new Vue({ el: "#app", router: router, }) </script> </body> </html>