Javascript Vue.js查找发出事件的组件

Javascript Vue.js查找发出事件的组件,javascript,vue.js,Javascript,Vue.js,我正在尝试使用一个表示购物项目的组件。 我的购物清单中的每一项都有一个组件。 我不知道在编辑子项(购物项目)时如何更新父项数据(购物列表) 购物清单 <template> <div id="app"> <shopping-item v-for="(item, index) in shoppingList" :key="index" :propsName=&qu

我正在尝试使用一个表示购物项目的组件。 我的购物清单中的每一项都有一个组件。 我不知道在编辑子项(购物项目)时如何更新父项数据(购物列表)

购物清单

<template>
  <div id="app">
    <shopping-item
      v-for="(item, index) in shoppingList"
      :key="index"
      :propsName="item.name"
      :propsQuantity="item.quantity"
      @shoppingItemEdited="handleEdit"
    ></shopping-item>
  </div>
</template>

<script>
import ShoppingItem from "./components/ShoppingItem.vue";

export default {
  name: "App",
  components: {
    ShoppingItem,
  },
  data() {
    return {
      shoppingList: [
        { name: "apple", quantity: 8 },
        { name: "banana", quantity: 3 },
        { name: "kiwi", quantity: 7 },
        { name: "peach", quantity: 5 },
      ],
    };
  },
  methods: {
    handleEdit(itemEdited) {
      // How to get the index of the shopping-item that has been updated ?
      // shoppingList[???] = itemEdited
      console.log(itemEdited);
      // => {name: "white peach", quantity: "6"}
    },
  },
};
</script>
  • 只需将索引传递给处理程序:
    @shoppingItemEdited=“handleEdit(index$event)”
  • 不,它不是“标准”-
    创建的
    钩子在创建组件时只调用一次,所以如果prop的值稍后发生更改(从父级更改),
    数据
    将不会更新。在您的情况下,这可能不是问题,但通常最好使用
    computed
  • 计算:{
    姓名:{
    get(){返回this.propsName},
    设置(值){
    此.$emit(“shoppingItemEdited”{
    名称:value,
    数量:这个,数量,
    }); 
    }
    }
    }
    
    …在父级中处理事件,更改将(通过道具)传播到子级

  • 只需将索引传递给处理程序:
    @shoppingItemEdited=“handleEdit(index$event)”
  • 不,它不是“标准”-
    创建的
    钩子在创建组件时只调用一次,所以如果prop的值稍后发生更改(从父级更改),
    数据
    将不会更新。在您的情况下,这可能不是问题,但通常最好使用
    computed
  • 计算:{
    姓名:{
    get(){返回this.propsName},
    设置(值){
    此.$emit(“shoppingItemEdited”{
    名称:value,
    数量:这个,数量,
    }); 
    }
    }
    }
    

    …在父级中处理事件,更改将(通过道具)传播到子级

    使用发射中的
    道具
    :key=“index”
    ?使用发射中的
    道具<代码>:key=“index”?
    <template>
      <div>
        <input v-model="name" placeholder="ex: banana" @change="updateParent" />
        <input
          v-model="quantity"
          type="number"
          placeholder="ex: 3"
          @change="updateParent"
        />
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          name: "",
          quantity: null,
        };
      },
      props: {
        propsName: String,
        propsQuantity: Number,
      },
      created() {
        this.name = this.propsName;
        this.quantity = this.propsQuantity;
      },
      methods: {
        updateParent() {
          this.$emit("shoppingItemEdited", {
            name: this.name,
            quantity: this.quantity,
          });
        },
      },
    };
    </script>
    
    this.name = this.propsName;
    this.quantity = this.propsQuantity;