Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have a modal component that I want to be able to insert programmatically when I want. There is a way to do this with Vue?

For example:

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

Then in any component I want to be able to do something like this:

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

});

Note: I don't want the modal template to be in every component that I need to use the modal. it just need for example to append the modal component to the body tag.

share|improve this question

I'd imagine the cleanest way of doing this will end up being via vuex.

Therefore you'd set the modal component within the root of your app, as you say before the body tag:

<div id="app">

    ...

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

</div>
</body>

Now create a vuex store which will allow you to toggle the modal along with I assume populating it's 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 set a computed prop for showModal (as the template for the root of your app contains the modals component):

import store from './vuex/store'

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

Set the modal component to at least watch the value of state.modalContent:

modal component

export default {

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

Now you can call the vuex store mutations from any component throughout your app to update its content and toggle its visibility:

example component

export default {

    mounted () {

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

        this.$store.commmit('toggleModal')
        ...
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.