删除 v-for 指令中的列表项

Delete list item in v-for directive

这里我有一个显示一个列表的组件。 单击列表项一侧的一个按钮可以删除列表的每个元素。

模板

    <div
    v-for="(question, index) in questions"
    :key="index"
    class="q-gutter-md row items-start">
      <q-input
      v-model="question.question"
      label="Domanda"
      lazy-rules
      :name="'question' + index"
      :rules="[lengthValidation]"
      ></q-input>

      <q-select
      v-model="question.answerType"
      :options="answerTypesList"
      label="Tipo di risposta"
      :name="'answerType' + index"
      ></q-select>

      <q-btn
      flat
      class="q-ml-sm"
      color="negative"
      icon="cancel"
      :label="index"
      @click="removeQuestion(index)" />
    </div>

脚本

    removeQuestion (evt, index) {
      console.log(index)
      this.questions.splice(index, 1)
    }

结果

注意:第一行不是列表的一部分

当我 "console.log" 从组件接收到 "index" 变量时,打印的值是 "undefined",但是如您所见,在 "delete" 符号的一部分中,索引是正确的。

我该如何解决这个问题?

此致

编辑于 2020 年 4 月 26 日 自 split 方法以来修改了脚本代码 returns 一个包含已删除项目的数组并从数组中删除该项目:

之前

this.questions = this.questions.splice(index, 1)

当前

this.questions.splice(index, 1)

您只从侦听器传递了一个值,即索引,因此该方法将在其第一个参数 evt 中接收该值。删除该参数以获取 index:

中的值
removeQuestion (index) {
  console.log(index)
  this.questions.splice(index, 1)
}

或者如果您想保留两个参数,请确保从侦听器传递 $event

@click="removeQuestion($event, index)"

您可能期望事件会自动传递,因为当您附加一个没有调用的处理程序时,Vue 将默认传递该事件。如:

@click="removeQuestion"

这会自动传递一个参数,$event。但是,如果您指定自己的调用(即 ()),那将不会发生。