[Vuejs]-How do I watch changes to an object? this.$set seems to capture only property update

1👍

Currently, myData watcher observes only an object. Object contains pointers to arrays as in JS Objects & Arrays are passed by reference not by copy. That’s why it can detect only changes in keys and with simple values. If you want to observe it deeper – I mean also those subarrays (or subobjects) – just use deep watch.

watch: {
  myData: {
    deep: true,
    handler (newVal) {
      console.log(`🔴localStorage`);
    }
  }
}

Another possible solution could be to use some Array.prototype operation to modify an array if it already exists. E.g:

methods: {
    onFoldChange(propertyName) {
      if (propertyName in this.myData && Array.isArray(this.myData[propertyName])) {
           this.myData[properyName].push(162) // Some random value
      } else {
           const newArr = [...]
           this.$set(this.myData, propertyName, newArr);
      }
    },
  }

Leave a comment