如何使用 Vue.js 从 $emit 有效负载中获取值

use*_*126 5 javascript vue.js vue-component vuejs2

我正在发出一个具有各种值的事件,从我的ConversationList(子组件)到ConversationModel(父组件)。

对话列表

getConversation(conversation_id, receiver_id, username, avatar){
  this.$emit('open-conversation', receiver_id, conversation_id, username, avatar);
}
Run Code Online (Sandbox Code Playgroud)

对话模式

Vue 开发工具输出

[2,1,"Jeff","http://i.pravatar.cc/52"]
Run Code Online (Sandbox Code Playgroud)

模板

<converstations-list v-if="showConversation == false" v-on:open-conversation="getConversation($event)"></converstations-list>
Run Code Online (Sandbox Code Playgroud)

方法

getConversation(event){
    console.log(event.payload[0] + event.payload[1] + event.payload[2] + event.payload[2])
},
Run Code Online (Sandbox Code Playgroud)

错误

“打开对话”的事件处理程序出错:“类型错误:无法读取未定义的属性‘2’”

我不明白。该事件正在触发,并且有一个devtools我无法访问的有效负载对象。我究竟做错了什么?

Bou*_*him 8

在从子组件发射到父组件的事件中,您将收到像您发射它们一样的参数:

所以$event从你的getConversation处理程序中删除:

<converstations-list v-if="showConversation == false" v-on:open-conversation="getConversation"></converstations-list>
Run Code Online (Sandbox Code Playgroud)

并实现getConversation方法如下:

 getConversation(receiver_id, conversation_id, username, avatar){
     // do whatever you want with that parameters
   }
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,效果很好。我很困惑为什么它会这样工作。 (2认同)