Vue modal component for limitless reusability

I am looking to create a modal wrapper that can dynamically inject components into it. The modal itself should handle tasks like closing, while the injected component is responsible for determining what is displayed and how data is handled. Here is my current approach:

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 sets modalVisible to true and takes a componentName as an argument. We then listen for this change, 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>

When I send a componentName to the watcher, I encounter the following error:

Unknown custom element:

It seems like the component I am trying to pass into my AppModal cannot be resolved. Am I doing something wrong?

Answer №1

In order for to function properly, it is essential to import and register all the components that will be used in the prop :is="...". Therefore, your modalComponent should include imports and registrations for all the components that will be invoked by

For instance, if you plan on utilizing Comp1 and Comp2 interchangeably, your modalComponent should look something like this:

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

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

In your template, you can then have

<component :is="modalComponent"/>

Best of luck.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble displaying Vue Toast messages?

I have been trying to incorporate a toast message into my code, but unfortunately, the message does not appear and there are no errors in the console. The code functions properly and the invitation is sent successfully. I have used similar code in other fi ...

How can you partially update an entity in TypeORM using a query runner?

Updating a user's name partially is simple with the repository save method: await this.repository.save({ id: 1, name: 'john' }); However, when attempting to do the same using queryrunner, all fields must exist which throws an error stating ...

Dynamically alter routing in Express by retrieving route paths from a JSON document

My goal is to dynamically update my route in Express using a JSON file that stores the specific link. The JSON data resides in articles.js and appears as follows: title: 'title1', link: 'title2', creator: 'user1', crea ...

When attempting to start a new React Native project using npx, I encountered an error stating "react-native: command not found"

After running 'npx react-native init MyProject' for the first time, it prompted that react-native would be downloaded, but I mistakenly terminated the process. Now, when I try again, it shows an error saying 'react-native: command not found& ...

React Date-Picker is unable to process a date input

Recently, I've been working on integrating a date picker into my application. I came across this helpful library that provides a date picker component: https://www.npmjs.com/package/react-date-picker So far, I have set up the component in the follow ...

What steps can be taken to resolve the error message "Echo is not recognized"?

Currently, I am handling a project with Laravel 7 along with Vue.js and Laravel-echo. The setup involved installing the Laravel Echo library using npm install --save laravel-echo pusher-js within my application. Additionally, the necessary code was include ...

Utilizing Filters to Dynamically Highlight and Unhighlight HTML in Angular

Currently, I am experimenting with creating a series of filters that can dynamically highlight and remove highlighting from generated HTML: Highlight filter: app.filter('highlight', function ($sce) { return function (str, termsToHighlight) ...

Sundays and last days are excluding React-big-calendar and dayjs longer events from being displayed

I've encountered a bug in my calendar view implementation. Long events are not displaying on Sundays or the ending day. Please refer to this image for reference: https://i.stack.imgur.com/V0iis.png Event details: Start time: Mon Aug 07 2023 15:44:00 ...

Warning: An unhandled promise error occurred due to a validation error

I've been facing an issue for the past few days. Currently, I'm diving into learning the MEAN stack, but while trying to create a user on MongoDB using Mongoose schema, I encountered this problem: (node:93337) UnhandledPromiseRejectionWarning: ...

Having trouble with a jQuery function that keeps throwing a TypeError about $(...) being null when trying to change an

I'm facing a frustrating issue right now - my hair is falling out as I try to understand why JQuery is constantly throwing a TypeError. I believe my call to replace an input value in the HTML is valid, but for some reason, it's not working. With ...

Is Javascript the best choice for managing multiple instances of similar HTML code?

I am currently facing the challenge of dealing with a lengthy HTML page consisting of around 300 lines of code. The majority of the code involves repetitive forms, each identical except for the ID (which varies by number). Is it considered appropriate or ...

The "track by" feature in Angular doesn't seem to be functioning properly when used with an array from $

Within the method of my factory, I am retrieving an array from the server using Angular's $resource: var resource = $resource("vm", { session: function() { return Auth.token(); }, all: '@all', vmId: '@vmId' ...

Issue with Vuetify: Unable to drag and drop all-day events in monthly calendar view

When using vuetify and v-calendar, only non-daily events can be dragged in week and day view (does not work at all in monthly view). I am looking to be able to move daily events (lasting the entire day, not just from 00:01 to 23:59) to another day while ...

Invoking a method within the same class in Typescript can be achieved by calling one method from another

I've recently delved into Typescript and I'm facing an issue when trying to call one method from another method within the same class. After researching this problem, some individuals suggested using "this" before the method name. However, in my ...

Adjusting the shadow on the inserted image

Currently, I am using fabric.js to manipulate images that are added to my canvas. The issue I am facing is with the shadow around the image not being even. The code I have tried so far is displayed below, but you can view what I am aiming for by clicking h ...

Ways to simulate a class instance that is being received from a file with a different class instance

I am struggling with a specific file in my project // src/history import { createBrowserHistory } from 'history' const history = createBrowserHistory(); export default history; The variable history represents an instance of the BrowserHistory cl ...

Tips for enhancing the efficiency of a three.js environment within Gatsby.js or react:

I am dealing with a straightforward three.js scene that is rendered using an useEffect hook. The scene loads a model using GLTFLoader(). On the page, there are three event listeners triggered on load. One calculates the browser's inner height, anothe ...

Creating Component Variants for Google Optimize A/B testing in Next.js

I've been attempting to create a component variant in Google Optimize beyond just text or color changes, but I haven't found a suitable method to do so yet. I'm looking for guidance on how to integrate/configure Optimize with my code in orde ...

Struggling to make the javascript function compatible with the drop-down menu

I'm encountering issues with making my JavaScript work properly alongside my HTML. Specifically, I want the "activity" drop-down box to function in conjunction with the "city" drop-down box. For instance, if I choose "Brisbane" and then select an acti ...

Error encountered with nested v-for in Vue.JS causing null and undefined values to be thrown

Question Conclusion: A Vue component I am working on has the following data setup: conversations: null, currentConversation: null, There is a method that runs on mounted() to retrieve the user's conversations: /** * Method to retrieve the user&ap ...