Paradigm
Paradigm

Reputation: 371

VueJS not picking up data passed

I'm very new to VueJS so expect this is very much a me problem but hoping for some guidance.

I have a Vue instance the person object in data contains some predefined data but I'm adding to the object when it's mounted. For whatever reason I cant understand it's not updating the DOM with the data inserted when mounted. I've checked the vue app and can confirm the person being added on the mounted method is being added correctly.

    new Vue({
    el: '#app',
    data: {
      people: {
        Dave: {'Age': 30, 'Plays': 5}
      }
    },

    mounted: function() {
      this.people['Rob'] = {'Age': 22, 'Plays': 24};
    }
    });
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <ul>
    <li v-for="(person, key) in people">
      {{ key }}: {{ person.Age }}
    </li>
  </ul>
</div>

I have a feeling this is either a Vue gotcha or I'm doing something really stupid.

Upvotes: 1

Views: 120

Answers (2)

Vamsi Krishna
Vamsi Krishna

Reputation: 31352

This is due to the change detection caveat

Instead you should be doing it like this:

new Vue({
el: '#app',
data: {
  people: {
    Dave: {'Age': 30, 'Plays': 5}
  }
},

mounted: function() {
  this.$set(this.people, 'Rob', Object.assign({}, { 'Age': 22, 'Plays': 24}));
 }
});

Here is the fiddle

I also recommed you go through array change caveats so you do not face any problems in the future

Upvotes: 1

NICO
NICO

Reputation: 1843

Or use a hook that fires before the element is mounted.

new Vue({
  el: '#app',
  data: {
    people: {
      Dave: {'Age': 30, 'Plays': 5}
    }
  },

  created: function() {
    this.people['Rob'] = {'Age': 22, 'Plays': 24};
  }
});

Upvotes: 0

Related Questions