【问题标题】:"You are binding v-model directly to a v-for iteration alias"“您将 v-model 直接绑定到 v-for 迭代别名”
【发布时间】:2017-07-26 13:15:04
【问题描述】:

刚刚遇到这个我以前没有遇到过的错误:“您将 v-model 直接绑定到 v-for 迭代别名。这将无法修改 v-for 源数组,因为写入别名是就像修改函数局部变量一样。考虑使用对象数组并在对象属性上使用 v-model。我有点困惑,因为我似乎没有做错任何事。与我之前使用的其他 v-for 循环的唯一区别是,这个循环更简单一些,因为它只是循环遍历字符串数组,而不是对象:

 <tr v-for="(run, index) in this.settings.runs">

     <td>
         <text-field :name="'run'+index" v-model="run"/>
     </td>

     <td>
        <button @click.prevent="removeRun(index)">X</button>
     </td>

 </tr>

错误消息似乎表明我实际上需要让事情变得更复杂一些,并使用对象而不是简单的字符串,这对我来说似乎不合适。我错过了什么吗?

【问题讨论】:

  • 如何在您的视图模型中定义settings
  • settings 是从服务器返回的 JSON 对象,包含一个名为 runs 的属性,最初是一个空数组。

标签: vue.js


【解决方案1】:

由于您使用的是v-model,因此您希望能够从输入字段更新run 值(我假设text-field 是一个基于文本输入字段的组件)。

消息告诉您不能直接修改 v-for 别名(run 是)。相反,您可以使用 index 来引用所需的元素。您可以在removeRun 中同样使用index

new Vue({
  el: '#app',
  data: {
    settings: {
      runs: [1, 2, 3]
    }
  },
  methods: {
    removeRun: function(i) {
      console.log("Remove", i);
      this.settings.runs.splice(i,1);
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.5.18/vue.js"></script>
<table id="app">
  <tr v-for="(run, index) in settings.runs">
    <td>
      <input type="text" :name="'run'+index" v-model="settings.runs[index]" />
    </td>
    <td>
      <button @click.prevent="removeRun(index)">X</button>
    </td>
    <td>{{run}}</td>
  </tr>
</table>

【讨论】:

  • 太棒了!做到了,谢谢,没有增加额外的复杂性。
  • 它应该在文档中。我很难找到它。
  • 关于如何处理索引更改的任何想法?在任何时候我的索引都可以改变......这就是我的结构:template.columns[0].columns[1].children[3].style.color
  • @CaioKawasaki 我无法从您的评论中理解这个问题。您可能应该提出一个新问题。
猜你喜欢
  • 2020-04-13
  • 2018-03-07
  • 2018-07-29
  • 2020-07-18
  • 2019-03-27
  • 2018-03-07
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多