Vue.js:监视对象的动态更改

Vue.js: Monitor Dynamic Changes To Object

本文关键字:动态 对象 js 监视 Vue      更新时间:2023-09-26

问题

侦听子组件未检测到对对象的更改。

上下文

我有一个空对象,它存储从API返回的值。此对象绑定到子组件中的属性。

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

每次调用此方法时,都会向对象中添加一个包含响应的命名数组。

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

在VueJS中,添加到对象的属性不是被动的。您需要使用vm.$set方法使其具有反应性:

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

您可以在此页面上阅读更多信息:深度反应性

对于Vue 1,它应该像这样构造,以允许Vue检测对象的更改:

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

参考:深度反应性