Ad

How To Bind Dynamic Inputted Values To V-for Input Fields In Vue.js

- 1 answer

I am attempting to build a simple Vue.js SPA that enables the user to render inputted values in individual input fields in a v-for loop. So far, I have my instance set up to return a few hard coded values to input fields in the loop (item: [{ name: 'John' },{ name: 'James' }]), but I want to dynamically input additional values and have those values render in new individual input fields. I have attempted to achieve this by adding a function that pushes my inputted values into the item array, but instead of generating new input fields with values I am getting only empty input fields. The problem is that I am not sure how to assign my new values to "name:" inside the array in order to them in individual input fields. Any recommendations on how to resolve this? See my code below. Thanks!

<template>
  <div id="app">
    <input v-model="newInput"/>
    <button @click="addItem()">add</button>
    <div v-for="list in item">
        <input type="text" v-model="list.name" />
        {{list.name}}
    </div>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () {
    return {
      newInput: '',
      item: [{ name: 'John' },{ name: 'James' }]
    }
  },
  methods: {
    addItem() {
      this.item.push(this.newInput);
    }
  }
}
</script>
Ad

Answer

In addItem method a string (this.newInput) is pushed to the array. You should push the object instead structured like other objects in the array:

addItem() {
  this.item.push({ name: this.newInput });
}
Ad
source: stackoverflow.com
Ad