Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

vue.js - "You are binding v-model directly to a v-for iteration alias"

Just run into this error I hadn't encountered before: "You are binding v-model directly to a v-for iteration alias. This will not be able to modify the v-for source array because writing to the alias is like modifying a function local variable. Consider using an array of objects and use v-model on an object property instead." I am a little puzzled, as I don't appear to be doing anythong wrong. The only difference from other v-for loops I've used before is that this one is a little simpler, in that it's simply looping through an array of strings, rather than objects:

 <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>

The error message would seem to suggest that I need to actually make things a little more complicated, and use objects instead of simple strings, which somehow doesn't seem right to me. Am I missing something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you're using v-model, you expect to be able to update the run value from the input field (text-field is a component based on text input field, I assume).

The message is telling you that you can't directly modify a v-for alias (which run is). Instead you can use index to refer to the desired element. You would similarly use index in removeRun.

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...