4

New to Vue.js. Not sure where I am going wrong here. I have a dynamic list of users which you can add to. I also have a select that I want to stay recent with any model changes to the users. However, when I change the user information, the select is not being updated. I've attached the code and a Fiddle.

HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>
<div id="app">
  <h1>Users</h1>
  <div v-for="user in users">
    User ID: <input type="text" v-model="user.id" /><br /> 
    First Name: <input type="text" v-model="user.firstName" /><br />
    Last Name: <input type="text" v-model="user.lastName" />
    <br />
  </div>
  <input type="button" value="Add User" v-on:click="addUser" />
  <br /><br />
  This select should stay synced with what is entered above<br />
  <select>
    <option v-for="user in users" v-bind:value="user.firstName">{{user.firstName}} {{user.lastName}}</option>
  </select>
</div>

JavaScript:

var app = new Vue({
    el: "#app",
    data: {
        users: [{}]
    },
    methods: {
        addUser: function() {
        this.users.push({});
      }
    }
});

Fiddle: https://jsfiddle.net/rmekuuc3/

1 Answer 1

5

This is a change detection caveat in Vue. Vue cannot detect when you add a property to an object that wasn't already on that object. Instead, you should write your code like this.

var app = new Vue({
    el: "#app",
    data: {
      users: [{id: null, firstName: null, lastName: null}]
    },
    methods: {
      addUser: function() {
        this.users.push({id: null, firstName: null, lastName: null});
      }
    }
});

Updated fiddle.

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.