Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I'm amazed by what vuejs brings to the table, but I'm hitting a wall at the following. I have an input text field with a v-model attached, and every time someone hits the "add" button, another input text get added to the DOM with the same v-model attached. I thought I'd then get an array of the v-model values, but it only gets the value of the first v-model input:

<label class="col-sm-2" for="reference">Referenties</label>
<div class="col-sm-6">
    <input v-model="find.references" class="form-control" type="text">
</div>
<div class="col-sm-2">
<button @click="addReference" class="form-control"><span class="glyphicon glyphicon-plus"></span>Add</button>                        

The html I append to the dom is triggered by the addReference method:

addReference : function (e) {
            e.preventDefault();

            console.log(this.find.references);

            div = '<div class="col-sm-6 col-md-offset-2 reference-row"><input v-model="find.references" class="form-control" type="text"></div>';

            $('#references').append(div);
        }

Is this something Vuejs can't do? Is there a different approach of gathering values from dynamic dom elements with Vuejs?

share|improve this question
up vote 2 down vote accepted

You're thinking too DOM, it's a hard as hell habit to break. Vue recommends you approach it data first.

It's kind of hard to tell in your exact situation but I'd probably use a v-for and make an array of finds to push to as I need more.

Here's how I'd set up my instance:

new Vue({
  el: '#app',
  data: {
    finds: []
  },
  methods: {
    addFind: function () {
      this.finds.push({ value: '' });
    }
  }
});

And here's how I'd set up my template:

<div id="app">
  <h1>Finds</h1>
  <div v-for="find in finds">
    <input v-model="find.value">
  </div>
  <button @click="addFind">
    New Find
  </button>
</div>

Here's a demo of the above: https://jsfiddle.net/a5t24gm3/1/

share|improve this answer
    
Aha! So by making finds an array, which allows you to create a v-for, you kind of tell vue it's going to be an array, opposed to expecting v-model single-value to array-value magic of vuejs! Thanks a bunch! Absolutely loving Vuejs. – Jan Vansteenlandt 1 min ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.