I want to create a dynamic form fields to add multiple names using vue js sample output -> https://prnt.sc/h6y0pf
here's my html
<div id="app">
<h1>Vue JS Multiple Fields Repeater</h1>
<div class="border" v-for="field in field1">
<input v-model="field.value" placeholder="Enter First Name">
<input v-model="field2.value" placeholder="Enter Last Name">
</div>
<button @click="AddField">
New Field
</button>
<pre>{{ $data | json }}</pre>
</div>
here's my vuejs
new Vue({
el: '#app',
data: {
field1: [] ,
field2: []
},
created: function() {
this.field1.push({ value: '' });
this.field2.push({ value: '' });
},
methods: {
AddField: function () {
this.field1.push({ value: '' });
this.field2.push({ value: '' });
}
}
});
I've created a jsfiddle here -> https://jsfiddle.net/0e3csn5y/2/
The problem is that only the first name can be populated everytime i add a new field. How can i also do that to last name field? How can we do the tricky part here?
It will be difficult to bind both input with same object in your current try, Use like this to bind first-name
and last-name
properly.
new Vue({
el: '#app',
data: {
fields: [{ first: '',last: '' }],
},
created: function() {
},
methods: {
AddField: function () {
this.fields.push({ first: '',last: '' });
}
}
});
.border {
border: 1px solid black;
padding: 3px;
margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.14/vue.js"></script>
<div id="app">
<h1>Vue JS Multiple Fields Repeater</h1>
<div class="border" v-for="field in fields">
<input v-model="field.first" placeholder="Enter First Name">
<input v-model="field.last" placeholder="Enter Last Name">
</div>
<button @click="AddField">
New Field
</button>
<pre>{{ $data | json }}</pre>
</div>
The reason you're having issue with this is because of some of limitations of javascript and their affect on reactivity.
I agree with the other response as to the ideal solution. However, here is one more option if you want to use two arrays.
the important parts:
v-for="i in field1.length"
this will loop 0 to length
then remove use of value in object, set using this.field1.push('')
and get using field1[i]
https://jsfiddle.net/0e3csn5y/4/
html:
<div id="app">
<h1>Vue JS Multiple Fields Repeater</h1>
<div class="border" v-for="i in field1.length">
<input v-model="field1[i]" placeholder="Enter First Name">
<input v-model="field2[i]" placeholder="Enter Last Name">
</div>
<button @click="AddField">
New Field
</button>
<pre>{{ $data | json }}</pre>
</div>
js:
new Vue({
el: '#app',
data: {
field1: [] ,
field2: []
},
created: function() {
this.field1.push('');
this.field2.push('');
},
methods: {
AddField: function () {
this.field1.push('');
this.field2.push('');
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With