1

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".

3
  • How are you "cloning" the field? Commented Oct 3, 2016 at 20:39
  • var newRow = lastRow.clone(); And then I'm tweaking the properties on the new row so that ID attributes are different, etc. Commented Oct 3, 2016 at 20:42
  • Hello Adam. did you ever manage to resolve this? currently stuck on similar issue. Also don't want to brute force in jquery.. Commented Jun 16, 2020 at 5:40

1 Answer 1

4

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:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.