如何将for循环中的元素传递给父组件?

问题描述 投票:0回答:1

Background我有一个子组件,该子组件遍历从父组件传递来的名为“ expenseButton”的数组。在此for循环中,是正在更新的元素。特别是“ expense”

子组件

<form class="container">
      <div class="buttonList" v-for="(expense, index) in expenseButton" :key="index">
        <button type="button" @click="expenseButtonClick(expense)">{{expense.expensesKey}}</button>

        <input class="textInput" v-model.number="expense.subExpense" type="number" />

      </div>
</form>

<script>
export default {
  props: {
    expenseButton: Array,
  },
  methods: {
    expenseButtonClick(expense) {
      expense.expensesValue = expense.expensesValue - expense.subExpense;
    }
}
}
</script>

问题我知道$ emit事件可以将数据传递给父级。但是,我试图找到最好的方法将数组的更新后的elements发送回父组件。

父组件数据

<template>
<expense-button :expenseButton="expenseButton"></expense-button>

</template>

<script>
export default {
  components: {
    "expense-button": Expenses
  },
  data() {
    return {
      expenseButton: [    
{"expensesKey":"rent","expensesValue":null,"subExpense":""},
{"expensesKey":"movies","expensesValue":null,"subExpense":""},
{"expensesKey":"clothes","expensesValue":null,"subExpense":""}
],
    };
  }
}
</script>
javascript vue.js vuejs2 components v-for
1个回答
0
投票

我认为您应该使用$ emit。子组件:

<form class="container">
      <div class="buttonList" v-for="(expense, index) in expenseButton" :key="index">
        <button type="button" @click="expenseButtonClick(expense)">{{expense.expensesKey}}</button>

        <input class="textInput" v-model.number="expense.subExpense" type="number" />

      </div>
</form>

<script>
export default {
  props: {
    expenseButton: Array,
  },
  methods: {
    expenseButtonClick(expense) {
      expense.expensesValue = expense.expensesValue - expense.subExpense;
      this.$emit("expense-btn-clicked", expense)
    }
  }
}
</script>

父组件:

<template>
  <expense-button :expenseButton="expenseButton" @expense-btn-clicked="btnClickedHandler"></expense-button>
</template>

<script>
export default {
  components: {
    "expense-button": Expenses
  },
  data() {
    return {
      expenseButton: [    
        {"expensesKey":"rent","expensesValue":null,"subExpense":""},
        {"expensesKey":"movies","expensesValue":null,"subExpense":""},
        {"expensesKey":"clothes","expensesValue":null,"subExpense":""}
      ],
    }
  },
  methods: {
    btnClickedHandler(e) {
      console.log(e)
    }
  }
}
</script>
© www.soinside.com 2019 - 2024. All rights reserved.