Javascript VueJS 2 - 如何使用 $emit 传递参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42986380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VueJS 2 - How to Pass Parameters Using $emit
提问by Moshe
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.
我正在使用 VueJS 2 处理一个模态组件。现在,它基本上可以工作——我点击一个按钮,模态打开等等。
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>
<modal name='myName'>CONTENT</modal>
And this would be the associate button:
这将是关联按钮:
<button @click="showModal('myName')"></button>
<button @click="showModal('myName')"></button>
What I need to figure out is how to pass the parameter of showModal to the modal component.
我需要弄清楚的是如何将 showModal 的参数传递给模态组件。
Here is the method that I'm using in the root vue instance (i.e, NOT inside my modal component):
这是我在根 vue 实例中使用的方法(即,不在我的模态组件中):
methods: {
showModal(name) { this.bus.$emit('showModal'); },
}
What I want to do is to access the name property in the component -- something like this:
我想要做的是访问组件中的 name 属性——像这样:
created() {
this.bus.$on('showModal', () => alert(this.name));
}
But this shows up as undefined.
但这显示为undefined.
So what am I doing wrong? How can I access the name property inside the modal component?
那么我做错了什么?如何访问模态组件内的 name 属性?
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
注意:如果您想知道 this.bus.$on 是什么,请参阅我之前提出的问题的以下答案:https://stackoverflow.com/a/42983494/7477670
回答by Bert
Pass it as a parameter to $emit.
将其作为参数传递给$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

