/user/foo/profile /user/foo/posts
+------------------+ +-----------------+
| User | | User |
| +--------------+ | | +-------------+ |
| | Profile | | +------------> | | Posts | |
| | | | | | | |
| +--------------+ | | +-------------+ |
+------------------+ +-----------------+
<div id="app">
<router-view></router-view>
</div>
const User = {
template: `
<div class="user">
<h2>User {{ $route.params.id }}</h2>
<router-view></router-view> // 在这里放入二级视图容器 <router-view></router-view>
</div>
`,
};
const Profile = { template: '<div>profile</div>' };
const Posts = { template: '<div>posts</div>' };
const routes = [
{
path: '/user/:id',
component: User,
// 加入 children 字段即可
children: [
{
path: 'profile',
component: Profile,
},
{
path: 'posts',
component: Posts,
},
],
},
];
const router = new VueRouter({
routes,
});
const routes = [
{
path: '/user/:id',
component: User,
// 加入 children 字段即可
children: [
{
path: '', // 空字符串
component: Profile 或 Posts,// 空路由默认显示哪个组件可自行取舍
},
{
path: 'profile',
component: Profile,
},
{
path: 'posts',
component: Posts,
},
],
},
];
const router = new VueRouter({
routes,
});