VueJS 2 - 如何使用 $emit 传递参数 [英] VueJS 2 - How to Pass Parameters Using $emit

查看:38
本文介绍了VueJS 2 - 如何使用 $emit 传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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:

这将是关联按钮:

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

我需要弄清楚的是如何将showModal的参数传递给模态组件.

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

这是我在根 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 是什么,请参阅我之前提出的问题的以下答案:https://stackoverflow.com/a/42983494/7477670

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.

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

这篇关于VueJS 2 - 如何使用 $emit 传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆