"您将v-model直接绑定到v-for迭代别名"

Joh*_*ore 30 vue.js

只是碰到我之前没有遇到的这个错误:"你将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>
Run Code Online (Sandbox Code Playgroud)

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

Roy*_*y J 65

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

该消息告诉您不能直接修改v-for别名(即run).相反,您可以index用来引用所需的元素.你会使用同样indexremoveRun.

new Vue({
  el: '#app',
  data: {
    settings: {
      runs: [1, 2, 3]
    }
  },
  methods: {
    removeRun: function(i) {
      console.log("Remove", i);
      this.settings.runs.splice(i,1);
    }
  }
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 优秀!这样做,谢谢,没有增加额外的复杂性. (4认同)
  • 它应该是文档.我很难找到它. (3认同)