Donnie
Donnie

Reputation: 6341

Vue.js: Monitor Dynamic Changes To Object

Problem

Changes to an object are not being detected by the listening child component.

Context

I have an empty object that is storing values as they come back from an API. This object is bound to a property in a child component.

data () {
  return {
    filterOperators: {}
  };
},

Each time this method is called, a named array containing the response is added to the object.

getfilterOperators: function (fieldName) {
  this.filterOperatorsAction(fieldName, response => {
    this.$data.filterOperators[fieldName] = response.Data;
  });
}

Upvotes: 0

Views: 661

Answers (2)

Donnie
Donnie

Reputation: 6341

For Vue 1, it should be constructed like this in order to allow Vue to detect the change to the object:

this.$set('filterOperators.' + fieldName, response.data);

Reference: Reactivity in Depth

Upvotes: 0

Hammerbot
Hammerbot

Reputation: 16324

In VueJS, properties added to objects are not reactive. You need to use the vm.$set method to make them reactive:

getfilterOperators: function (fieldName) {
  this.filterOperatorsAction(fieldName, response => {
    this.$set(this.filterOperators,fieldName,response.data);
  });
}

You can read more information on this page: Reactivity in Depth

Upvotes: 1

Related Questions