之前学习大神后台系统时发现一个问题没搞懂,仔细看了 vue-router 文档才明白
先举个小例子:
123456789101112131415161718192021222324252627282930313233343536373839 <script src="https://unpkg.com/vue/dist/vue.js"></script><script src="https://unpkg.com/vue-router/dist/vue-router.js"></script><div id="app"><p><router-link to="/user/foo">/user/foo</router-link><router-link to="/user/foo/profile">/user/foo/profile</router-link><router-link to="/user/foo/posts">/user/foo/posts</router-link></p><router-view></router-view></div>const User = {template: `<div class="user"><h2>User {{ $route.params.id }}</h2><router-view></router-view></div>`}const UserHome = { template: '<div>Home</div>' }const UserProfile = { template: '<div>Profile</div>' }const UserPosts = { template: '<div>Posts</div>' }const router = new VueRouter({routes: [{ path: '/user/:id', component: User,children: [// UserHome will be rendered inside User's <router-view>// when /user/:id is matched{ path: '', component: UserHome },// UserProfile will be rendered inside User's <router-view>// when /user/:id/profile is matched{ path: 'profile', component: UserProfile },// UserPosts will be rendered inside User's <router-view>// when /user/:id/posts is matched{ path: 'posts', component: UserPosts }]}]})const app = new Vue({ router }).$mount('#app')看以上代码,有没有发现 html 里面有
<router-view></router-view>
,js 里面也有,按道理来说组件就是通过<router-view></router-view>
渲染出来的,为什么会有两个呢?到底渲染到哪里呢?仔细看 https://router.vuejs.org/zh-cn/essentials/nested-routes.html,可以看到,嵌套的路由组件会先渲染到父级的
<router-view></router-view>
中。如果父级路由没有该标签,那么子路由的组件不会被渲染出来,小知识,还是要仔细看文档啊。