vue-router 多层嵌套问题

// 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
                  }
               ]
            }
         ]
      }
   ]
});

第三层嵌套时,依然显示第二层路由的内容,请问是什么原因?

阅读 11.7k
2 个回答

首先说下,不要发截图,直接发代码,这样我可以直接用你的代码修改。

你的路由标签定义错了,第三级路由需要在UserPosts这个组件里匹配 <router-view></router-view>,但是你的UserPosts里没有写<router-view></router-view>,而且你在User组件里写了两个 <router-view></router-view>会被匹配两次。

先把template模板修改一下吧。

路由配置参考下面的代码吧。

new Router({
  routes: [{
    {
      path: '/user/:id',
      component: User,
      children: [{
        path: '/user/:id/posts',
        component: UserPosts,
        children: [{
          path: '/user/:id/posts/third',
          component: Third
        }]
      }]
    }
  }]
})
新手上路,请多包涵

请问对应有几层文件,几个文件? 能否把文件目录结构贴出来看看?谢谢!

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题