vue-router:嵌套命名视图问题。附加组件不可见

时间:2019-01-05 23:16:23

标签: javascript vue.js 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不可见。 为什么?

1 个答案:

答案 0 :(得分:0)

当您这样指定路线时,

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

UserSettingsTestComponent被视为同级组件,因此在渲染时,它将在最顶层指定的默认router-view旁边查找一个命名为router-view的元素。 div为#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来更改声明方式。

请参见working example