简体   繁体   English

如何在 vue 的 v-for 循环中显示带有按钮的 div onclick?

[英]How to show a div onclick with a button inside a v-for loop in vue?

Background背景

I have a v-for loop that contains a pair of buttons and inputs.我有一个包含一对按钮和输入的 v-for 循环。 The buttons contains an @click event that is suppose to show the corresponding input.这些按钮包含一个 @click 事件,该事件应该显示相应的输入。

Problem问题

When the buttons are clicked it shows all the input instances instead of the corresponding input to the button clicked.单击按钮时,它会显示所有输入实例,而不是单击按钮的相应输入。

 <div class="buttonFor my-3" v-for="(expense,index) in expenseButton" :key="index">
            <input type="submit" @click="showInput(expense)" :value="expense.expensesKey" />
            <input v-show="needEdit" v-model.number="expense.subExpense" type="number" />
          </div>
data() {
    return {
      expenseButton: [],
      needEdit: false
    };
  }
methods: {

    showInput() {
      this.needEdit = !this.needEdit;
    }
}

I think it's better you keep track of the chosen id.我认为最好跟踪所选的 ID。 you could edit your data to receive chosen id like:您可以编辑您的数据以接收选择的 ID,例如:

data() {
    return {
      expenseButton: [],
      chosenExpenseId: null
    };
}

your show input receives the index instead:您的 show 输入改为接收索引:

methods: {
    showInput(index) {
      this.chosenExpenseId = index;
      // if want to make the button to hide input once clicked back
      // this.chosenExpenseId = this.chosenExpenseId !== index ? index : null;
    }
}

at your template you pass the index and validates input show condition as:在您的模板中,您传递索引并验证输入显示条件为:

<input type="submit" @click="showInput(index)" :value="expense.expensesKey" />
<input v-show="index === chosenExpenseId" v-model.number="expense.subExpense" type="number" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM