Home > OS >  v-model inside loop showing the wrong value
v-model inside loop showing the wrong value

Time:11-13

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  v-for="(i, idx) in products" :key="idx">
    <div>
      <button @click="addRow" >
      add
      </button>
      <button @click="removeRow(idx)" >
      remove
      </button>
    </div>
    <div >
      <input v-model="products[idx].name" type="text"  id="name" placeholder="name">
    </div>
      <div >
      <input v-model="products[idx].category" type="text"  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 here the screenshot enter image description here

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

CodePudding user response:

Its not necessary to access the item using index inside v-for instead you can use the iterator itself

<div id="app">
  <div  v-for="(product, idx) in products" :key="idx"> <!-- line changed -->
    <div>
      <button @click="addRow" >
      add
      </button>
      <button @click="removeRow(idx)" >
      remove
      </button>
    </div>
    <div >
      <input v-model="product.name" type="text"  id="name" placeholder="name"> <!-- line changed -->
    </div>
      <div >
      <input v-model="product.category" type="text"  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
    },
},
  • Related