我在開發中使用 vue 版本2.6.14并且我回圈物件資料陣列并在這些回圈中使用 v-model 并且想法用戶應該能夠動態添加或洗掉資料但是當我添加或洗掉陣列時 v-模型未顯示正確資料。例如,如果我在陣列索引 1 上填充物件,則其余物件具有相同的值。請看下面的代碼和截圖:
html
<div id="app">
<div class="row mb-3" v-for="(i, idx) in products" :key="idx">
<div>
<button @click="addRow" class="btn btn-small btn-primary">
add
</button>
<button @click="removeRow(idx)" class="btn btn-small btn-danger">
remove
</button>
</div>
<div class="mb-3">
<input v-model="products[idx].name" type="text" class="form-control" id="name" placeholder="name">
</div>
<div class="mb-3">
<input v-model="products[idx].category" type="text" class="form-control" id="category" placeholder="category">
</div>
</div>
</div>
js
new Vue({
el: '#app',
data: function() {
return {
products: [{
name: null,
category: null
}],
product: {
name: null,
category: null
}
}
},
methods: {
addRow: function(){
this.products.push(this.product);
},
removeRow: function(index){
this.products.splice(index, 1);
}
}
})
這里是截圖

并且期望是藍框(圖片上的藍框)中的欄位不應該跟隨紅框
這里的小提琴
任何人都可以幫助我嗎?
提前致謝
uj5u.com熱心網友回復:
無需使用內部索引訪問專案,v-for而是可以使用迭代器本身
<div id="app">
<div class="row mb-3" v-for="(product, idx) in products" :key="idx"> <!-- line changed -->
<div>
<button @click="addRow" class="btn btn-small btn-primary">
add
</button>
<button @click="removeRow(idx)" class="btn btn-small btn-danger">
remove
</button>
</div>
<div class="mb-3">
<input v-model="product.name" type="text" class="form-control" id="name" placeholder="name"> <!-- line changed -->
</div>
<div class="mb-3">
<input v-model="product.category" type="text" class="form-control" id="category" placeholder="category"> <!-- line changed -->
</div>
</div>
</div>
addRow還將方法修改為
methods: {
addRow(){
this.products.push({...this.product}); // Using rest operator to create a new reference
},
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532014.html
