// 1.定义路由组件
var Foo = { template : '<div>foo</div>' };
var Bar = { template : '<div>bar</div>' };
var User = {
template : `<div class="user">
<h2>User {{ $route.params.id }}</h2>
<router-view></router-view>
<div class="third">
<router-view></router-view>
</div>
</div>`
};
var UserProfile = { template : '<div>UserProfile</div>' };
var UserPosts = { template : '<div>UserPosts</div>' };
var Third = { template : '<div>第三层</div>' };
// 2.定义路由
// 3.创建router实例,然后传routes配置
var router = new VueRouter({
routes : [
{ path:'/foo', component : Foo},
{ path:"/bar", component : Bar},
{ path:'/user/:id', component : User,
children : [
{
// 当 /user/:id/profile 匹配成功,
// UserProfile 会被渲染在 User 的 <router-view> 中
path : "profile",
component : UserProfile
},
{
// 当 /user/:id/posts 匹配成功
// UserPosts 会被渲染在 User 的 <router-view> 中
path : 'posts',
component : UserPosts,
children : [
{
// 当 /user/:id/profile/third 匹配成功,
// third 会被渲染在 User 的 <router-view> 中
path : 'third',
component : Third
}
]
}
]
}
]
});
第三层嵌套时,依然显示第二层路由的内容,请问是什么原因?
首先说下,不要发截图,直接发代码,这样我可以直接用你的代码修改。
你的路由标签定义错了,第三级路由需要在
UserPosts
这个组件里匹配<router-view></router-view>
,但是你的UserPosts
里没有写<router-view></router-view>
,而且你在User
组件里写了两个<router-view></router-view>
会被匹配两次。先把template模板修改一下吧。
路由配置参考下面的代码吧。