Reputation: 8617
I'm using VueJS with a form, and I'm having trouble with dynamically added input fields.
The form starts with a single input field, where someone can enter a number, along the lines of:
<input type="text" name="line[1]" v-model="line[1]">
There is then another part of the page which is supposed to display a running total of the amounts entered in the lines. I'm using a computed property to accomplish this.
It works fine with all of the fields that are present when the page loads. But the user can click a button to clone the previous field. This dynamically added field does not get included in the calculations. I'm guessing that may be for two reasons. First is that by the time the element is cloned, it no longer has the "v-model" attribute set (I could be wrong about this; it doesn't show up in Chrome developer tools inspection). Second, I don't believe Vue knows about the element since it was added after the Vue instance was created.
Is there a good way to handle this? I could brute force it with jQuery, I'm sure, but there must be a "Vue way".
Upvotes: 1
Views: 4071
Reputation: 20490
My suggestion is:
<input v-for="line in lines" v-model="line" name="line[]">
Set lines
as an array in your data
, and push
new elements into it.
new Vue({
data: {
lines: ['initial text']
},
methods: {
addLine: function() {
this.lines.push(this.lines[this.lines.length - 1])
}
}
})
You may also check if you are not under a "change detection caveat". Please, check...
VueJS 1:
VueJS 2:
Upvotes: 4