在Vue.js中如何使用多个路由器视图,其中一个在另一个组件内?

wra*_*him 7 javascript vue.js vue-router vuejs2

我有一个Vue.js单页面应用程序,其中有一个<router-view/>用于呈现不同页面的主导航栏.

像这样的东西:

<main-header/> <!-- navigation links -->
<transition name="slide-fade" mode="out-in">
  <router-view/> <!-- different pages -->
</transition>
Run Code Online (Sandbox Code Playgroud)

在其中一个页面中,我有一个侧栏,它有更多的导航链接(<router-link/>就像主导航栏一样.

像这样的东西:

<sidebar/> <!-- navigation links -->
<div class="content">
  <transition name="slide-fade" mode="out-in">
    <router-view/> <!-- content beside the sidebar -->
  </transition>
</div>
Run Code Online (Sandbox Code Playgroud)

当我单击侧边栏导航链接时,我希望侧边栏旁边的内容以及要更改的URL更改.但是,我丢失了侧边栏,只是获取要在内容部分中呈现的组件.

我如何达到预期的效果?如何<router-view/>在其他组件中使用多个s,如上例所示?

Tua*_*ham 12

你需要使用named views.为name视图提供属性.

<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
Run Code Online (Sandbox Code Playgroud)

并配置他们像

const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        default: Foo,
        a: Bar
      }
    }
  ]
})
Run Code Online (Sandbox Code Playgroud)

请参阅官方文档.


小智 8

边栏消失的原因是<router-view>除了之外,所有组件都在第一个中渲染<main-header>

您应该通过children在侧边栏路由器中进行配置来使用嵌套路由器,例如:

const router = new VueRouter({
  routes: [
    { path: '/your-sidebar-url', component: your-sidebar-page,
      children: [
        {
          // A will be rendered in the second <router-view>
          // when /your-sidebar-url/a is matched
          path: 'a',
          component: A
        },
        {
          // B will be rendered in the second <router-view>
          // when /your-sidebar-url/b is matched
          path: 'b',
          component: B
        }
      ]
    }
  ]
})
Run Code Online (Sandbox Code Playgroud)

嵌套路线中的更多信息


Jos*_*eie 7

@adoug 的回答对我有帮助。

但就我而言,我将两个路由器视图命名为:

我这样做是为了修复它:

<router-view name='a'/>
<router-view name='b'/>
Run Code Online (Sandbox Code Playgroud)

你有,FatherComponent.vue在你内心的某个地方a,你有第二个

我这样做是为了修复它:

const router = new VueRouter({
    routes: [
        { path: '/your-sidebar-url',
            components: {
                a: FatherComponent //you sidebar main component in 'a' name of routed-view
            },
            children: [
                {
                    // A will be rendered in the second <router-view>
                    // when /your-sidebar-url/a is matched
                    path: '/child-path/a',
                    components: {
                        b: ChildComponentA //note that 'b' is the name of child router view
                    }
                },
                {
                    // B will be rendered in the second <router-view>
                    // when /your-sidebar-url/b is matched
                    path: '/child-path/b',
                    components: {
                        b: ChildComponentB //note that 'b' is the name of child router view
                    }
                }
            ]
        }
    ]
})
Run Code Online (Sandbox Code Playgroud)