首页 > 解决方案 > vue-router:嵌套命名视图问题。附加组件不可见

问题描述

我在 vue-router 文档中找到了这个例子:

https://jsfiddle.net/posva/22wgksa3/?fbclid=IwAR2WITnr6cmA_3rUgOCCvPrHASKfSW9QsvEKv4HrxBmuDUN1VmWSWufCtAI

const router = new VueRouter({
   mode: 'history',
   routes: [{ 
       path: '/settings',
       // You could also have named views at tho top
       component: UserSettings,
       children: [{
           path: 'emails',
           component: UserEmailsSubscriptions
           }, {
           path: 'profile',
           components: {
               default: UserProfile,
               helper: UserProfilePreview
           }
       }]
   }]
})

我试图做这样的事情:

https://jsfiddle.net/pt9o6h8e/

const router = new VueRouter({
   mode: 'history',
   routes: [{ 
       path: '/settings',
       components: {
           default: UserSettings,
           test: TestComponent
       }
       children: [{
           path: 'emails',
           component: UserEmailsSubscriptions
           }, {
           path: 'profile',
           components: {
               default: UserProfile,
               helper: UserProfilePreview
           }
       }]
   }]
})

但 TestComponent 不可见。为什么?

标签: javascriptvue.jsvue-router

解决方案


当你像这样指定你的路线时,

{ 
  path: '/settings',
  // You could also have named views at tho top
  components: {
    default: UserSettings,
    test: TestComponent
  }
}

UserSettings并且TestComponent被认为是同级组件,因此在渲染时,它将在您在最顶层 div 上指定router-view的默认值旁边查找一个名为.router-view#app

但是,您将模板放入<router-view name="test" /> 其中, UserSettings 因此找不到router-view要渲染TestComponent 的对象。

要解决此问题,请将test路由器视图UserSettings#app.

<div id="app">
  <h1>Nested Named Views</h1>
  <router-view></router-view>
  <router-view name="test" class="us__content us__content--helper"/>
</div>

或者,如果您想将其保留在内部,请通过移动您的任一子路由来UserSettings更改您声明它的方式。test: TestComponent

请参阅工作示例


推荐阅读