VueJS 2 - How to Pass Parameters Using $emit

ⅰ亾dé卋堺 提交于 2019-11-29 11:07:07

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/42986380/vuejs-2-how-to-pass-parameters-using-emit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!