如果路由元数据键设置为 true,则 Vue 将组件渲染为特定路由中的模态

Vue render component as modal in specific route if route metadata key is set to true

我正在使用 vue-router 并尝试创建如下功能:

我希望能够在路由器路由中指定组件是否应以模态呈现。如果它在 Modal 中呈现,请保持下面的每个组件(在 modal-mask 下)原样。 我创建了一个模态包装器组件,它具有基本的模态结构和 slot 在其模态体内,所以我要渲染的组件应该放在 slot 中。但是如何实现呢。 Vue-Router 是否有该功能的选项。

路由器路线:

{
  path: '/customers/:clientId',
  component: customerView
  meta: {
    auth: true,
  },
},
{
  path: '/customers/:clientId/addAddress',
  component: dataViewAdd
  meta: {
    openInModal: true,
    auth: true,
  },
},

因为如果组件应该在模态内渲染同时覆盖之前的路由器视图,我想我需要 2 个路由器视图。

<router-view class="normal-view"></router-view>
<router-view class="modal-view" name="modal-view"></router-view>

如果每个模态路由中显示的组件未在非模态上下文中使用,那么您只需修改模态路由组件的模板(dataViewAdd),使模态组件成为模板。但是你提到你会在不同的情况下重用这些组件(所以一条路线可能在模态内使用 dataViewAdd 而另一条路线可能不在模态内使用 dataViewAdd)。

可以为每个组件创建包装模态版本,但这会变得混乱;看起来您只想能够指定 openInModal: true 并使其适用于任何组件。

您还提到模态框在 DOM 中的位置无关紧要(否则我建议使用 portal-vue 之类的东西来协助解决此问题)。

首先,您需要更改路由器配置,以便模态路由是您希望在其下方保持可见的组件的子组件。确保 customerView 里面有一个 <router-view>

创建一个辅助函数,其中 returns 组件的模态包装版本并将其用作路由组件。这不使用 openInModal 元 属性,但它以类似的方式工作。

以下代码未经测试。

import Modal from './modal.vue';

function wrapInsideModal(childComponent) {
  return {
    functional: true,
    render(h) {
      return h(Modal, [h(childComponent)]);
    },
  };
}

// Routes
{
  path: '/customers/:clientId',
  component: customerView,
  meta: {
    auth: true,
  },
  children: [
    {
      path: 'addAddress',
      component: wrapInsideModal(dataViewAdd),
    },
  ],
},