繁体   English   中英

VueJS:如何在数组的 for 循环中使用绑定值?

[英]VueJS: How to use a binding value within a for loop of an array?

我有一个字符串数组:

myList: ['First item', 'Second item']

我想添加第三个,甚至更多。 我有一个将空字符串推送到数组的方法:

this.myList.push('')

在 Vue 对象上使用 .push 是可以的

现在看起来像这样:

['First item', 'Second item', '']

我现在可以编辑。 但是,它没有绑定到数组。 添加另一个项目时,该值将丢失并返回一个空字符串。

 var app = new Vue({ el: '#app', data: function() { return { myList: ['First item', 'Second item'] } }, methods: { remove(index) { Vue.delete(this.myList, index) }, add() { this.myList.push('') } } })
 <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> <div id="app"> <p v-for="(listItem, index) in myList" class="my-2 field" :key="index"> <input type="text" :value="listItem" :key="index" /> <button @click.prevent="remove(index)">✕</button> </p> <p> <button @click.prevent="add()">Add</button> </p> </div>

尝试了以下方法:

如上:

<input
  type="text"
  :value="listItem"
  :key="index"
/>

没有钥匙,同样:

<input
  type="text"
  :value="listItem"
/>

使用(不正确的)绑定,不回显值:

<input
  type="text"
  :value="myList[index]"
/>

使用v-bind

<input
  type="text"
  v-bind:value="listItem"
/>

还有一把钥匙:

<input
  type="text"
  v-bind:value="listItem"
  v-bind:key="index"
/>

我很肯定我会以错误的方式解决这个问题。 希望你能看到我试图达到的行为。


更新刚刚尝试使用v-model ,但我收到此错误:

您将 v-model 直接绑定到 v-for 迭代别名。 这将无法修改 v-for 源数组,因为写入别名就像修改函数局部变量一样。 考虑使用对象数组并在对象属性上使用 v-model 。

拥有一个具有一个值的对象数组可能更容易吗?

您应该使用 v-model 对您的输入进行 2 路绑定,并且您必须使用 myList[index] 因为 v-bind 指令需要属性值而不是 v-for 别名(如 listItem)。 尝试这个:

 var app = new Vue({ el: '#app', data: function() { return { myList: ['First item', 'Second item'] } }, methods: { remove(index) { Vue.delete(this.myList, index) }, add(listItem) { this.myList.push('') } } })
 <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> <div id="app"> <p v-for="(listItem, index) in myList" class="my-2 field" :key="index"> {{myList[index]}} <input type="text" v-model="myList[index]" /> <button @click.prevent="remove(index)">✕</button> </p> <p> <button @click.prevent="add()">Add</button> </p> </div>

输入未与数组元素绑定。 尝试这个。

 var app = new Vue({ el: '#app', data: function() { return { myList: ['First item', 'Second item'] } }, methods: { remove(index) { Vue.delete(this.myList, index) }, add() { this.myList.push('') } } })
 <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> <div id="app"> <p v-for="(listItem, index) in myList" class="my-2 field" :key="index"> <input type="text" v-model="myList[index]" :key="index" /> <button @click.prevent="remove(index)">✕</button> </p> <p> <button @click.prevent="add()">Add</button> </p> </div>

JSFiddle: https ://jsfiddle.net/32d41epw/2/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM