[Vuejs]-Vue – dynamically registered models?

1👍

You should be able to use a v-model that will allow your input fields to change the value in the list :

<input 
   type="number" 
   v-for="(entry, index) in list"
   :key="'input-field-'+entry.id"
   name="entry.id" 
   v-model="entry.initial_value"
   :id="'entry-id__' + entry.id" 
/>

When a new value is set by the user, it should modify this precise value in your list object.

Then keep your last line as is:

<input name="total" :value="summedTotal" />

with summedTotal being a computed value summing the values of your list.

If you don’t want to change your original list, you can make a deep copy first and then use copiedList for your v-model:

data {
  copiedList : JSON.parse(JSON.stringify(this.list))
}

Here is a Snippet that works:

new Vue({
  el: '#app',
  data: {
    list: [{
        id: 1,
        initial_value: 3
      },
      {
        id: 2,
        initial_value: 1
      },
      {
        id: 3,
        initial_value: 7
      },
      {
        id: 4,
        initial_value: 2
      },
    ]
  },
  computed: {
    summedValued() {
      return this.list.reduce((acc, c) => {
        return acc + parseInt(c.initial_value || 0);
      }, 0)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(entry, index) in list" :key="'input-field-'+entry.id">
    ID {{entry.id}}: <input type="number" name="entry.id" v-model="entry.initial_value" :id="'entry-id__' + entry.id" />
  </div>
  TOTAL :{{summedValued}}

</div>

Leave a comment