问题描述
我正在使用VueJS 2处理模态组件。现在,它基本上可以工作 - 我点击按钮并打开模态等。
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>
这将是关联按钮:
< button @click =showModal('myName')>< / button>
我需要弄清楚的是如何传递参数showModal到模态组件。
What I need to figure out is how to pass the parameter of showModal to the modal component.
这是我在root vue实例中使用的方法(即,不在我的模态组件中):
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'); },
}
我想要做的是访问组件中的name属性 - 像这样:
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));
}
但这显示为 undefined
。
那么我做错了什么?如何访问模态组件中的name属性?
So what am I doing wrong? How can I access the name property inside the modal component?
注意:如果您想知道this.bus。$ on是什么,请参阅以前的答案我问的问题:
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
推荐答案
将其作为参数传递给 $ 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
这篇关于VueJS 2 - 如何使用$ emit传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!