Vue.js 嵌套路由与默认孩子

新手上路,请多包涵

我对 Vue.js 2 中的默认子路由有疑问。

当我最初访问 localhost/listings 时,它会正确加载 index.vue 和 map.vue 作为孩子。

当我使用 router-link 导航到 localhost/listings/1,然后使用 router-link 返回到 localhost/listings 时,它仍然加载 show.vue 模板。 这不应该发生?

我没有导航卫士或任何应该干扰的东西。无论如何要纠正这个?

我的路线:

 window.router = new VueRouter({
  routes: [
    ...

    {
      path: '/listings',
      name: 'listing.index',
      component: require('./components/listing/index.vue'),
      children: [
        {
          path: '',
          component: require('./components/listing/map.vue')
        },
        {
          path: ':id',
          name: 'listing.show',
          component: require('./components/listing/show.vue')
        }
      ]
    },

    ...
  ]
});

原文由 andershagbard 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 339
2 个回答

也许尝试重新安排孩子们,路线按照他们从上到下匹配的顺序被触发,所以这应该有望解决它:

 window.router = new VueRouter({
    routes: [

    ...

    {
        path: '/listings',
        name: 'listing.index',
        component: require('./components/listing/index.vue'),
        children: [
            {
                path: ':id',
                name: 'listing.show',
                component: require('./components/listing/show.vue')
            }
            {
                path: '',
                component: require('./components/listing/map.vue')
            },
        ]
    },

    ...

  ]
});

只是为了澄清一点,你的 path: '' 本质上是一个“包罗万象”,这可能就是为什么当它位于顶部时它会立即被发现,因此路由器永远不会进一步传播到 :id 路线。

原文由 K3TH3R 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您想要默认子路由,则不应命名“父”路由器,因此使用 :to="{name: 'listing.index'}" ,使用默认子路由的名称(例如 :to="{name: 'listing.map'}" )。

代码应如下所示:

 window.router = new VueRouter({
routes: [

    ...

    {
        path: '/listings',
        component: require('./components/listing/index.vue'),
        children: [
            {
                path: '',
                name: 'listing.map'
                component: require('./components/listing/map.vue')
            },
            {
                path: ':id',
                name: 'listing.show',
                component: require('./components/listing/show.vue')
            }
        ]
    },

    ...

  ]
});

原文由 Sadraque Santos 发布,翻译遵循 CC BY-SA 3.0 许可协议

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