dynamically add or remove multiple input fields with vue

Solutions on MaxInterview for dynamically add or remove multiple input fields with vue by the best coders in the world

showing results for - "dynamically add or remove multiple input fields with vue"
Emilia
06 Feb 2019
1<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" rel="stylesheet"/>
2<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
3
4<div id=app>
5  <div class="form-group" v-for="(input,k) in inputs" :key="k">
6    <input type="text" class="form-control" v-model="input.name">
7    <input type="text" class="form-control" v-model="input.party">
8    <span>
9      <i class="fas fa-minus-circle" @click="remove(k)" v-show="k || ( !k && inputs.length > 1)">Remove</i>
10      <i class="fas fa-plus-circle" @click="add(k)" v-show="k == inputs.length-1">Add fields</i>
11    </span>
12  </div>
13  <button @click="addCandidate">
14    Submit
15  </button>
16</div>
17<script>
18new Vue({
19  el: '#app',
20
21  data () {
22    return {
23      inputs: [{
24        name: '',
25        party: ''
26      }]
27    }
28  },
29
30  methods: {
31    add () {
32      this.inputs.push({
33        name: '',
34        party: ''
35      })
36      console.log(this.inputs)
37    },
38
39    remove (index) {
40      this.inputs.splice(index, 1)
41    },
42
43    addCandidate () {
44      axios
45        .post('/candidates', {
46          my_prop_name: JSON.stringify(this.inputs)
47        })
48        .then(response => {})
49        .catch(error => {})
50    }
51  }
52})
53</script>