繁体   English   中英

Vue 可重用的模态包装器

[英]Vue reusable modal wrapper

我想要一个模态包装器,我可以将组件注入其中,因此模态负责诸如关闭之类的事情,但是注入的组件负责显示的内容以及对数据的处理。 到目前为止,我有这个解决方案,

const Modal = namespace("Modal");

@Component 导出默认 class AppModal 扩展 Vue {

public component: any = null;

@Modal.State
public modalVisible!: boolean;
@Modal.State
public modalComponent!: string;

get injectedComponent() {
    return this.modalComponent;
}

@Modal.Mutation
public hideModal!: () => void

@Watch('injectedComponent')
onModalComponent(componentName: string) {
    if(!componentName) return;
    debugger;
    Vue.component(componentName, () => import(`./components/${componentName}`))
    this.component = componentName;
}

store 中的 showModal 方法,使 modalVisible 并获取一个 componentName,我们监听这个变化并导入组件,并使用动态组件将其注入到 modal 中。

<template>
<v-dialog v-model="modalVisible" class="muc-modal" max-width="350" persistent>
    
    <v-card>
        <component :is="modalComponent"/>
    </v-card>

</v-dialog>

无论我发送给观察者的组件名称,我都会收到以下错误,

未知的自定义元素:

就像它无法解析我想要发送到我的 AppModal 的组件。 我做错了什么吗?

要得到要工作,您必须导入并注册您将在 prop:is="..." 中传递的所有组件。 因此,您的 modalComponent 必须对所有将被调用的组件进行导入和注册

例如,如果您将交替使用组件 Comp1 和 Comp2,则您的 modalComponent 中应该有如下内容

import Comp1 from '<path-to-Comp1>
import Comp2 from '<path-to-Comp2>

@Component({
    components: {
        Comp1,
        Comp2,
    }
})
export default class AppModal extends Vue {
    ...
    ...
    ...
    <You fill in modalComponent with Comp1 or Comp2>
    ...
    ...
    ...
}

在您的模板中,您可以拥有

<component :is="modalComponent"/>

祝你好运。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM