简体   繁体   English

Vue 可重用的模态包装器

[英]Vue reusable modal wrapper

I am wanting to have a modal wrapper that I can inject components into, so the modal is responsible for things like being closed, but the injected component is repsonsible what is show, and what is done with the data.我想要一个模态包装器,我可以将组件注入其中,因此模态负责诸如关闭之类的事情,但是注入的组件负责显示的内容以及对数据的处理。 So far I have this solution,到目前为止,我有这个解决方案,

const Modal = namespace("Modal");

@Component export default class AppModal extends Vue { @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;
}

The showModal method in the store, makes the modalVisible and takes a componentName, we listen for this change and import the component, and use a dynamic component to inject it into the modal. 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>

Whatever componentName I send to the watcher I get the following error,无论我发送给观察者的组件名称,我都会收到以下错误,

Unknown custom element:未知的自定义元素:

It's like it can't resolve the component I wanting to send into my AppModal.就像它无法解析我想要发送到我的 AppModal 的组件。 Am I doing something incorrectly?我做错了什么吗?

To get要得到to work, you must import and register all the components that you will be passing in the prop:is="...".要工作,您必须导入并注册您将在 prop:is="..." 中传递的所有组件。 So, you modalComponent must have imports and registrations for all the components that will be called by因此,您的 modalComponent 必须对所有将被调用的组件进行导入和注册

For example, if you will be using the components Comp1, and Comp2 alternatively, you should have something like the following in your 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>
    ...
    ...
    ...
}

And in your template you can have在您的模板中,您可以拥有

<component :is="modalComponent"/>

Good luck.祝你好运。

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

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