如何丰富 Vue.js 中的事件数据

How to enrich event data in Vue.js

我有一个 Parent.vue,我将对象发送到 Child 组件,然后不时通过 this.$emit('updateItem', item).

取回更新的项目
<template>
  <div>
    <Child
      v-for="(item, index) in items"
      :key="index"
      :item="item"
      @updateItem="updateItem"
      // @updateItem="updateItem(index, dataFromChildComponent)" // this is what i would like to do
    />
  </div>
</template>

<script>
export default {
  name: 'Parent',

  data() {
    return {
      items: [] // List of objects
    }
  },

  methods: {
    updateItem (index, data) {
      // Receive the data and the index
    }
  }
}
</script>

我 运行 一直关注的问题是如何在 Parent 的项目列表中找到对象以更新正确的对象。我想丰富这些数据以添加例如一个索引,以便能够在列表中找到该项目。 有什么方法可以实现这一点,或者它实际上是将索引向下传播到 Child 以便再次发出它的正确方法吗?对我来说感觉像是一种反模式。

将您的事件侦听器更新为 @updateItem="data => updateItem(index, data)" 应该可以。假设您已经从子组件发出数据(即类似 this.$emit('updateItem', somedata))的数据。

您有多种选择可以实现:

  1. 您可以将道具索引作为子组件传递,然后在子组件中发送包含更新索引和更新值的对象。
  2. 您可以将当前代码更改为如下所示:@updateItem="updateItem(index, $event)" 其中 $event 是更新值