【问题标题】:Vue-router and multiple routes in same page?Vue路由器和同一页面中的多个路由?
【发布时间】:2021-10-15 01:59:28
【问题描述】:

我们正在创建一个基于 Vue 的网络应用程序,它在历史模式下使用 vue-router。一切都适用于在不同页面之间导航,但现在我们被要求在虚拟对话中打开一些页面,这会导致问题。最初我们尝试使用 iframe,但这会产生加载影响。

请注意,“虚拟对话”只是一个 div,旨在位于其余内容之上,装饰为一个窗口,可以显示 Vue 应用程序中的其他页面。这不是真正的浏览器级对话。

我们构建网站的方式:

  • components/ContentDialogue.vue
  • layout/MainLayout.vue
  • 页数/
    • MyPage.vue
    • MyPage2.vue
    • MyPage3.vue
  • router/index.js
  • App.vue
  • main.js

这里 MainLayout 有一个<router-view/>,所以当我们输入 a 路径时它会显示相应的内容。

对话打破了一切,因为从技术上讲,它需要能够显示框架中的任何其他页面。这导致了这样一个想法,MainLayout.vue 变为:

<template>
  <div class="layout main-layout">
    <div class="page-container">
      <router-view />
    </div>
    <div v-if="showDialogue" class="dialogue-page-container">
      <router-view />
    </div>
  </div>
</template>

Vue 路由器在 router/index.js 中设置,并在主目录中提供:

  const app = {
    router,
    render: h => h(App)
  };

  const vue = new Vue(app);
  vue.$mount('#app');

虽然这在概念上看起来不错,但我不确定如何让它真正发挥作用。对于对话,我们可以通过传递给 MainLayout 的事件来指示它打开,或者将其包含在查询值 such as /mypage?popup=/mypage2 中,但是这如何转化为路由器和布局?

谁能建议我们如何才能做到这一点?

【问题讨论】:

  • 尝试在命名路由器视图next.router.vuejs.org/guide/essentials/named-views.html 中显示模式,但基本上你的方法不会像这样工作,你必须重构你的逻辑。
  • 我在重构我的逻辑方面还不错,但你这么说是在想什么?
  • 您无法从模式中提供页面。如果你这样做了,那么它作为一个模态有什么意义。
  • 这不是一个真正的对话,而是一个模拟窗口的 div,位于其余内容之上,同时显示路线中列出的页面。已更新我的问题。

标签: javascript vue.js vuejs2 vue-router


【解决方案1】:

同时显示多个视图而不是嵌套它们,例如创建带有侧边栏视图和主视图的布局。这就是命名视图派上用场的地方。您可以拥有多个并为每个插座命名,而不是在您的视图中只有一个插座。没有名称的路由器视图将被默认为其名称。

<router-view class="view left-sidebar" name="LeftSidebar"></router-view>
<router-view class="view main-content"></router-view>
<router-view class="view right-sidebar" name="RightSidebar"></router-view>

一个视图是使用一个组件来渲染的,因此多个视图需要多个组件用于同一条路由。确保使用 components(带有 s)选项:

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      components: {
        default: Home,
        // short for LeftSidebar: LeftSidebar
        LeftSidebar,
        // they match the `name` attribute on `<router-view>`
        RightSidebar,
      },
    },
  ],
})

完整的解释见:https://next.router.vuejs.org/guide/essentials/named-views.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2012-12-20
    • 1970-01-01
    • 2019-10-24
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多