[Vuejs]-Vue.set doesn't update object

3👍

Vue.set is used as a workaround for the fact that Vue does not detect when a property is added to an object. So, it seems like you have the right idea: that the newData property doesn’t initially exist on the this.data.key1 object, and that you’ll need to use Vue.set to add the property and make it reactive.

In your code, Vue.set(this.data, 'key1', ch) is saying set the key1 property of this.data to ch and make it reactive, so that Vue can keep track of it. However, since the value of ch is just the this.data.key1 object with a new newData property, Vue is still unaware that that property is getting added to the object.

What you want to do is set the value of the newData property on this.data.key1, so you would need to do that like so:

Vue.set(this.data.key1, 'newData', 'text');

Here’s a working example:

new Vue({
  el: '#app',
  data() {
    return {
      data: {
        'key1': {
          value: true
        },
        'key2': {
          value: false
        }
      }
    }
  },
  mounted() {
    setTimeout(() => {
      Vue.set(this.data.key1, 'newData', 'text')
    }, 3000);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <div v-for="(value, key) in data">
    {{value.value}} {{value.newData}}
  </div>
</div>

Leave a comment