vue中为什么要有路由嵌套啊,一般的路由不就行了吗?我们可以看一个很简单的例子,页面效果是这样的:
html文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> </head> <body> <div id="app"> <router-link to="/user">父组件1</router-link> <router-link to="/register">父组件2</router-link> <router-view></router-view> </div> <script> // 父组件1 let user = { template: `<h1>user</h1>` } // 父组件2 let register = { template: ` <div> <router-link to="/register/tab1">tab1</router-link> <router-link to="/register/tab2">tab2</router-link> <router-view></router-view> </div> ` } // 子组件1 let tab1 = { template: `<h1>tab1</h1>` } //子组件2 let tab2 = { template: `<h1>tab2</h1>` } // 路由实例 let router = new VueRouter({ routes: [ { path: "/user", component: user }, { path: "/register", component: register, children: [ // { path: "/register/tab1", component: tab1 }, // { path: "/register/tab2", component: tab2 }, ] }, { path: "/register/tab1", component: tab1 }, { path: "/register/tab2", component: tab2 }, ] }) // vue实例 new Vue({ el: '#app', data: { message: '页面加载于 ' + new Date().toLocaleString() }, router }) </script> </body> </html>
当我们点击父组件2,就会在最上面的那个占位符<router-view>这里展示register组件,下图所示:
问题来了,如果我们再点击tab1呢?因为有两个<router-view>,你觉得tab1组件内容会展示在哪个<router-view>占位符里?
答案是取决于你的/register/tab1这个路由是写在哪里?如果是放在外面,那么tab1就展示在第一个<router-view>;如果写成/register路由的嵌套路由,才会展示在第二个<router-view>;所以嵌套路由的作用就是让新的页面内容展示在子组件的占位符中;