[Vuejs]-How to track changed Valued from array of objects in vuejs

0๐Ÿ‘

โœ…

  • At first create a child component for each row
  • Pass each row to component
  • Handle the single object inside the component instead of handling an array of objects in parent

See this example:

    Vue.component('child', {
  props: {
    value: { type: Object, default: () => ({}) }
  },
  data: function() {
    return {
      selfValue: null
    }
  },
  watch: {
    value: {
      handler(value) {
        this.selfValue = value
      },
      immediate: true,
      deep: true
    },
    selfVaue: {
      handler(value) {
        // you can also validate value then emit it
        this.$emit('input', value)
      },
      deep: true
    },
    'selfValue.quantity'() {
      this.selfValue.price = 0
    }
  },
  template: `
     <div class="d-flex justify-content-between">
        <label>
          Title:
          <input type="text" v-model="selfValue.title" class="form-control" />
        </label>
        <label>
          Quantity:
          <select v-model="selfValue.quantity" class="form-control">
            <option value="A">A</option>
            <option value="B">B</option>
          </select>
        </label>
        <label>
          Price:
          <input type="tel" v-model="selfValue.price" class="form-control" />
        </label>
     </div>
    `
})


new Vue({
  el: '#app',
  data: {
    rows: []
  },
  methods: {
    add() {
      this.rows.push({ title: '', quantity: '', price: 0 })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div id="app" class="container">
  <h2 class="mb-3">Rows:</h2>

  <div v-for="row,i in rows">
    <child v-model="row"></child>
    <hr class="mt-1 mb-1" />
  </div>
  
  <button @click="add" class="mb-3">
    ADD
  </button>
  
  <pre>{{ rows }}</pre>
  
</div>

Leave a comment