在vue.js中在数组和多个文本输入之间创建双向绑定 [英] Create a two-way binding in vue.js between an array and multiple text inputs
问题描述
我的数据存储在数组中.对于每个数组项,都应在表单中输入一个文本.当用户键入文本输入之一时,应使用新值更新数组.
My data is stored in an array. For each array item, there should be a text input in the form. When the user types into one of the text inputs, the array should be updated with the new values.
<div class="form-group" v-for="synonym in row.synonyms">
<input type="text" class="form-control" v-model="synonym" />
</div>
这是一个小提琴: https://jsfiddle.net/eywraw8t/122210/
这个想法是,当您在其中一个文本框中键入内容时,数组值(在小提琴中显示如下)也应该更新,但不会更新.
The idea is when you type into one of the textboxes, the array value (shown below in that fiddle) should also update, but it doesn't.
推荐答案
检查控制台后,您会发现以下错误:
Upon inspecting the console, you would find the following error:
您是将v-model直接绑定到v-for迭代别名..这将无法修改v-for源数组,因为写入别名就像修改本地函数一样多变的.考虑使用对象数组,并在对象属性.
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.
意思是,我们需要为 v-model
提供对同义词及其索引的直接引用:
Meaning, we need to give v-model
access to a direct reference to the synonym and its index:
new Vue({
el: "#app",
data: {
row: {
synonyms: [
"abc",
"def",
"ghj",
]
}
},
methods: {
}
})
body {
font-family: 'Exo 2', sans-serif;
}
#app {
margin: auto;
}
<div id="app">
<h2>Items</h2>
<div class="form-group" v-for="(synonym,i) in row.synonyms">
<input type="text" class="form-control" v-model="row.synonyms[i]" />
</div>
<br>
<h3>
The text below should change if yout type inside the textboxes:
</h3>
<p>
{{ JSON.stringify(row)}}
</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
这篇关于在vue.js中在数组和多个文本输入之间创建双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!