“您将 v-model 直接绑定到 v-for 迭代别名"; [英] "You are binding v-model directly to a v-for iteration alias"
问题描述
刚刚遇到这个我以前没有遇到过的错误:您将 v-model 直接绑定到 v-for 迭代别名.这将无法修改 v-for 源数组,因为写入别名是就像修改函数局部变量一样.考虑使用对象数组并在对象属性上使用 v-model."我有点困惑,因为我似乎没有做错任何事.与我之前使用过的其他 v-for 循环的唯一区别是,这个循环稍微简单一点,因为它只是遍历字符串数组,而不是对象:
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?
推荐答案
由于您使用的是 v-model
,您希望能够更新 run
值来自输入字段(text-field
是基于文本输入字段的组件,我假设).
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).
该消息告诉您不能直接修改 v-for
别名(run
是).相反,您可以使用 index
来引用所需的元素.您可以在 removeRun
中类似地使用 index
.
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>
这篇关于“您将 v-model 直接绑定到 v-for 迭代别名";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!