首页 > 解决方案 > 编辑 v-for 中的项目

问题描述

我正在尝试编辑v-for指令中的项目,但这似乎不像我预期的那样工作。首先,这是标记和组件方法:

<div class="card goal-item" v-for="goal in goals">
  <div v-if="!goal.edit" class="card-body">
    <p>
      {{ goal.value }}
      <span class="far fa-fw fa-edit float-right action" v-on:click="editGoal(index)"></span>
    </p>
  </div>
  <div v-else class="card-body">
    <div class="input-group">
      <input class="form-control" type="text" v-model="goal.value" v-on:keyup.enter="submitEditGoal(index)" />
      <div class="input-group-append">
        <button class="btn btn-primary" type="button" v-on:click="submitEditGoal(index)"><span class="far fa-fw fa-check"></span></button>
      </div>
    </div>
  </div>
</div>

methods: {
  editGoal(index){
    this.goals[index].edit = true;
  },
  submitEditGoal(index){
    this.goals[index].edit = false;
  }
}

每当用户按下按钮进行编辑时,v-else都不会触发。如果我edit在更改属性后记录它,editGoal(index)它确实会说true,但如果我打印出属性 ( {{ goal.edit }}),它仍然会说false

这是不可能的还是我做错了什么?

标签: vue.js

解决方案


您尝试做的事情的想法应该可以正常工作。您会遇到奇怪的行为,因为您使用:而不是引用您的方法@,这导致这些方法在处理模板时实际执行,而不是将它们绑定到您想要的事件。

看看这个小提琴:https ://jsfiddle.net/e7jv0wyc/

你会想像这样改变你的代码。请注意,有 3 个替换:with @

<div class="card goal-item" v-for="goal in goals">
  <div v-if="!goal.edit" class="card-body">
    <p>
      {{ goal.value }}
      <span class="far fa-fw fa-edit float-right action" @click="editGoal(index)"></span>
    </p>
  </div>
  <div v-else class="card-body">
    <div class="input-group">
      <input class="form-control" type="text" v-model="goal.value" @keyup.enter="submitEditGoal(index)" />
      <div class="input-group-append">
        <button class="btn btn-primary" type="button" @click="submitEditGoal(index)"><span class="far fa-fw fa-check"></span></button>
      </div>
    </div>
  </div>
</div>

推荐阅读