Issue
Im using vue version 2.6.14 in development and I do looping array of object data and use v-model inside those loop and the idea user should have ability to add or remove the data dynamically but when I add or remove the array the v-model not showing correct data. for example if I fill the object on array index 1, the rest object have same value. please see the following code and screenshot:
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);
}
}
})
And the expectation is the field in the blue box (blue box on the picture) shouldn't follow the red box
here the fiddle
Anyone can help me?
Thanks in advance
Solution
Its not necessary to access the item using index inside v-for
instead you can use the iterator itself
<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>
Also modify the addRow
method to be
methods: {
addRow(){
this.products.push({...this.product}); // Using rest operator to create a new reference
},
},
Answered By - Amaarockz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.