简体   繁体   中英

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 {

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.

<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. Am I doing something incorrectly?

To getto work, you must import and register all the components that you will be passing in the prop:is="...". So, you modalComponent must have imports and registrations for all the components that will be called by

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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