Creating Vue.js components dynamically

Is it possible to programmatically insert a modal component in Vue?

For instance:

Vue.component('modal', {...})

Then, in any component, is there a way to do something like this:

Vue.component('login', {
  methods: {  
    openLoginModal() {
       // Create the component modal and pass the props
     }
  }

});

Important Note: I am looking for a solution where the modal template does not need to be included in every component that needs to use the modal. It should just involve appending the modal component to the body tag as needed.

Answer №1

In my opinion, the best way to achieve this would likely be through vuex.

To do this, you would place the modal component at the root of your app, just before the closing body tag:

<div id="app">

    ...

    <modal v-if"showModal" inline-template>
        <div v-html="modalContent"></div>
    </modal>

</div>
</body>

Next, create a vuex store that will handle toggling the modal and setting its content:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

new Vuex.Store({
    state: {
        showModal: false,
        modalContent: '',
    },
    mutations: {
        toggleModal: (state) => {
            state.showModal = !state.showModal
        },
        setModalContent: (state, content) => {
            state.modalContent = content
        },
    },
})

Register the store with your app and create a computed property for showModal:

import store from './vuex/store'

new Vue({
    el: '#app',
    store,
    computed: {
        showModal () {
            return store.state.showModal
        },
        ...
})

Ensure that the modal component is watching the value of state.modalContent:

modal component

export default {

    computed: {
        modalContent () {
            return this.$store.state.modalContent
        },
        ...

Now, you can use the vuex store mutations in any component to update the modal's content and toggle its visibility:

example component

export default {

    mounted () {

        this.$store.commmit('setModalContent', '<h1>hello world</h1>')

        this.$store.commmit('toggleModal')
        ...

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

Modal containing react-select dropdown opens successfully

I am currently facing an issue with my custom modal that contains 2 react-select components. The modal body is set up to auto scroll when the content exceeds its size, but the problem arises when the dropdowns of the react-select components open within the ...

After a certain time has passed, an event will occur once a div element has been assigned

Is there a way to show div2 only after div1 has been given the '.selected' class for a set duration, and then hide it again when div1 loses the '.selected' class? What would be the most efficient approach to achieve this? ...

Utilizing service-based global objects in Angular applications

Upon entry into my application, the GlobalApplicationController initializes several services that are utilized throughout the entire application, such as subscribing to sockets. It would be quite beneficial to have a CurrentUser object available - however, ...

Tips for assigning a Custom Formik Component's value to the Formik value

I'm currently integrating Formik into my form alongside Google Places auto-complete feature. My goal is to display the places auto-complete functionality as a custom component within the Formik field. form.js <Formik initialValues={location:" ...

Error: The session ID is not currently active

I encountered a problem with my tests failing when running them on TFS, showing the following error: WebDriverError: No active session with ID Failed: No active session with ID Interestingly, these same tests are passing locally. Everything was working ...

Tips for updating components dynamically in VueJS

Looking to create a seamless app experience in vue.js where users can switch between views without any page reloading. What's the optimal approach for achieving this functionality and why is this current code not working as expected? Appreciate your h ...

vue Passing data to a Vue component and retrieving the selected value

Within my summary route, each nested route features a header containing a radio group. To display this header on all nested routes, I have utilized summary.vue located in the root of the pages folder and included <nuxt-child>. pages/summary.vue &l ...

Inaccurate data is being shown by the Ajax method

I have a question that I haven't been able to find a satisfactory answer for: Recently, I started learning about AJAX methods and I'm trying to post some information processed by a php page named page.php. In my HTML file, I've included th ...

Recreating dropdown menus using jQuery Clone

Hey there, I'm facing a situation with a dropdown list. When I choose "cat1" option, it should display sub cat 1 options. However, if I add another category, it should only show cat1 options without the sub cat options. The issue is that both cat 1 a ...

Refreshing Vue.js single-page application while transitioning to different routes

I am currently working on a project that involves Vue.js and Spring Boot. I have noticed that every time I switch to a different route using Vue routing, my page reloads. To navigate to the client-side route, I am using the following code snippet: @Control ...

Invoke the identical function in between two functions that make asynchronous AJAX calls

I seem to be a little lost at the moment. The code snippet below illustrates my intent, which is to use the insertChilds() function to insert child elements in the DOM in a cascading manner (or at least that's what I'm aiming for...). The challe ...

Searching through multiple columns in datatables

I encountered an issue with searching multiple columns in my serverside datatables. Individual column searches work fine, but when trying to search on more than one column simultaneously, the filter does not function as expected. For example, searching by ...

Is it possible to prevent the selected option from being available in other select lists using AngularJS?

Can anyone help me figure out how to disable an option in one select list when it is selected in another using AngularJS? I have set up a select list for From Year and To Year with ng-repeat, which is working fine. Now, I just need to implement the functio ...

The focus behavior of React refs varies across different browsers such as Chrome, Firefox, and IE

While working with refs in react, I observed that the .focus() method behaves differently in Chrome and Firefox. https://i.stack.imgur.com/rjSsZ.png In this sandbox https://codesandbox.io/s/a-guide-to-react-refs-2nd-example-vl9sj?file=/src/Ref.js I have ...

the integration of shapes in three.js is malfunctioning

There has been a dynamic change in the path. The previous render function was as follows (where LENGTH, getPosition(), RADIUS, MATERIAL, and SCENE have already been set) var prevPosition = getPosition(); for(var i =0; i < LENGTH; i++) { drawPath(g ...

Pull the Bootstrap radio value from hyperlink buttons

Is anyone else having trouble retrieving values of radio buttons using jQuery? Here are the radio buttons in question: <div class="input-group"> <div id="radioBtn" class="btn-group"> <a class="btn btn-warning radio-selector btn ...

Issue with border spacing functionality

I'm having some difficulty with my border spacing in CSS. No matter what size I specify, it doesn't seem to have any effect. I just want to use a border for the top line. Here is my CSS: p { border-spacing: 5000px; text-align: right; ...

Modify the height of an element in real-time using jQuery

I'm looking to dynamically adjust the height of a div based on another element, but only if that element does not have the class collapsed (which is used in a Bootstrap toggle collapse feature). The initial setup seems to work fine, however, when I i ...

Is it better to parse HTML in PHP or JavaScript for an iPhone web application?

I am in the process of creating a web application for iPhone/iPod touch. I need to incorporate an external HTML file and extract specific data from it. One approach is to handle this on the server side by creating a separate page that echoes the desired d ...

Having trouble dynamically adding HTML elements in JQuery

I am dynamically adding HTML elements during runtime using an AJAX call from a JavaScript file. Currently, I am attempting to use a combo box drop-down element to display a list of data. Here is how I am trying to achieve this in my script: $("#myList") ...