【问题标题】:VueJS Watcher is not triggered while watching deep object changes观察深层对象变化时不会触发 VueJS Watcher
【发布时间】:2021-01-28 10:12:54
【问题描述】:

我有一个可以重现我的问题的代码框:codesandbox example watcher not triggering

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

export default {
  defaultSection1: {
    displayName: 'Action',
  },
  defaultSection2: {
    displayName: 'Thriller',
  },
}

我在我的组件中导入这个对象。

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

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,
    },
  },

为什么观察者没有被触发,而数据显然正在改变?

我注意到的另一件很奇怪的事情是,在Vue 3.0 中,观察者被完全相同的代码触发。

Codesandbox in Vue 2.6.11, watcher not triggering.

Codesandbox in Vue 3.0, watcher IS triggered with exactly the same code.

【问题讨论】:

    标签: javascript node.js vue.js vuejs2 vuejs3


    【解决方案1】:

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

    this.$set(this.data,newSectionId, {displayName: 'Custom'})
    

    这个问题在 Vue 3 中得到解决。你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 2022-07-16
      相关资源
      最近更新 更多