VueJS 2 - How to Pass Parameters Using $emit

I am working on a modal component using VueJS 2. Right now, it basically works -- I click on a button and the modal opens, etc.

What I want to do now is create a unique name for the modal and associate the button with that particular button.

This is what I have in mind. The modal has a unique name property:

<modal name='myName'>CONTENT</modal>

And this would be the associate button:

<button @click="showModal('myName')"></button>

What I need to figure out is how to pass the parameter of showModal to the modal component.

Here is the method that I'm using in the root vue instance (i.e, NOT inside my modal component):

methods: {
    showModal(name) { this.bus.$emit('showModal'); },
}

What I want to do is to access the name property in the component -- something like this:

created() {
    this.bus.$on('showModal', () => alert(this.name));
}

But this shows up as undefined.

So what am I doing wrong? How can I access the name property inside the modal component?

NOTE: If you are wondering what this.bus.$on is, please see the following answer to a previous question that I asked: https://stackoverflow.com/a/42983494/7477670

Answers:

Answer

Pass it as a parameter to $emit.

methods: {
    showModal(name) { this.bus.$emit('showModal', name); },
}

created() {
    this.bus.$on('showModal', (name) => alert(name));
}

Also, if you want to give the modal a name, you need to accept it as a prop in the modal component.

Vue.component("modal",{
    props:["name"],
    ...
})

Then I assume you will want to do something like,

if (name == this.name)
    //show the modal

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.