Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/420.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 监视深度对象更改时不会触发VueJS监视程序_Javascript_Node.js_Vue.js_Vuejs2_Vuejs3 - Fatal编程技术网

Javascript 监视深度对象更改时不会触发VueJS监视程序

Javascript 监视深度对象更改时不会触发VueJS监视程序,javascript,node.js,vue.js,vuejs2,vuejs3,Javascript,Node.js,Vue.js,Vuejs2,Vuejs3,我得到了一个代码沙盒,它复制了我的问题: 我正在处理一个依赖于对象的组件,该对象具有可以动态添加到该对象的数据,因此,例如,在一个单独的.js文件中,我导出以下对象: export default { defaultSection1: { displayName: 'Action', }, defaultSection2: { displayName: 'Thriller', }, } 我在组件中导入此对象 我从Lodash获得了一个去抖动器设置,这样当数据发生

我得到了一个代码沙盒,它复制了我的问题:

我正在处理一个依赖于对象的组件,该对象具有可以动态添加到该对象的数据,因此,例如,在一个单独的
.js
文件中,我导出以下对象:

export default {
  defaultSection1: {
    displayName: 'Action',
  },
  defaultSection2: {
    displayName: 'Thriller',
  },
}
我在组件中导入此对象

我从Lodash获得了一个去抖动器设置,这样当数据发生变化时,它只会在两秒钟后触发一次观察者。观察者被触发对于对象中已经存在的数据来说非常好(在我的示例中键入输入文本框,观察者被触发)。但是,当我向对象动态添加数据时,观察者根本不会被触发。只有在来回更改路由时,数据才会更新,但不会触发观察者。为什么会这样?当数据被动态添加到对象时,我可以做些什么来触发观察程序

methods: {
    fetchAndUpdateData(){
      console.log('Fetching data...')
    },
    addCustomSection(){
      //The watcher should be triggered when this function is called
      const newSectionId = Math.floor(Math.random() * 1000); 
      this.data[newSectionId] = {
         displayName: 'Custom'
      }
    }
  },
  computed: {
    dataWatcher() {
      return this.data;
    },
    updateData() {
      return debounce(this.fetchAndUpdateData, 2000);
    },
  },
  watch: {
    dataWatcher: {
      handler() {
        console.log('Watcher triggered')
        this.updateData();
      },
      deep: true,
    },
  },
当数据明显改变时,为什么不触发观察者

另一件我注意到的非常奇怪的事情是,在
VUE3.0
中,监视程序被触发时使用的代码与完全相同


.

在vue 2中,更新数组中的项目或对象中的嵌套字段时存在反应性问题,要解决此问题,必须使用
此。$set()
方法:

this.$set(this.data,newSectionId, {displayName: 'Custom'})
这个问题在Vue 3中得到了解决。你可以这样做:

  const newSectionId = Math.floor(Math.random() * 1000); 
      this.data[newSectionId] = {
         displayName: 'Custom'
      }