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

比如:

<main-header/> <!-- navigation links -->
<transition name="slide-fade" mode="out-in">
  <router-view/> <!-- different pages -->
</transition>

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

比如:

<sidebar/> <!-- navigation links -->
<div class="content">
  <transition name="slide-fade" mode="out-in">
    <router-view/> <!-- content beside the sidebar -->
  </transition>
</div>

当我点击侧栏导航链接时,我希望侧栏旁边的内容和url都发生变化.然而,我丢失了侧边栏,只得到了要在内容部分呈现的组件.

我如何达到预期的结果?如何使用多个<router-view/>,其中一个在另一个组件内,如上面的示例?

推荐答案

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

您应该通过在侧栏路由中配置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
        }
      ]
    }
  ]
})

更多信息请点击nested routes

Vue.js相关问答推荐

设置Vite Vue 3需要多个应用程序输出目录

Vuejs 通过数据键迭代复杂对象

在 vue.js 中添加新类时样式不适用

将props传递给设置时的VueJS 3组合API和TypeScript类型问题:类型上不存在属性 user用户

指定一个 vue-cli vue.config.js 位置

更新 vue.js 中的数据属性/对象

Vue更改宽度和内容

在 vue/vuex(/flux?) 中使用 ES6 类是一种反模式吗?

取消选中单选按钮

vue 在 v-model 之后执行 @click

v-if inside v-for - 在两列中显示项目列表

触发子函数

异步方法不等待函数

如何从 vue 组件调用 App.vue 中的方法

了解 Nuxt.js 中的State状态和Getters:Getters不起作用

Vue3在按钮单击时以编程方式创建组件实例

将登录页面包含在单页应用程序中是否不安全?

beforeCreate 挂钩中的 Vue 2.1 调用方法不起作用

根据nuxt中的url参数动态加载组件

在 vue.js 应用程序中将静态内容(例如国家代码)存储在哪里?