vue.js $watch array of objects

后端 未结 4 1848
甜味超标
甜味超标 2021-02-01 13:58
mounted: function() {
  this.$watch(\'things\', function(){console.log(\'a thing changed\')}, true);
}

things is an array of objects

4条回答
  •  死守一世寂寞
    2021-02-01 14:41

    There is a more simple way to watch an Array's items without having deep-watch: using computed values

    {
      el: "#app",
      data () {
        return {
          list: [{a: 0}],
          calls: 0,
          changes: 0,
        }
      },
      computed: {
        copy () { return this.list.slice() },
      },
      watch: {
        copy (a, b) {
          this.calls ++
          if (a.length !== b.length) return this.onChange()
          for (let i=0; i

    https://jsfiddle.net/aurelienlt89/x2kca57e/15/

    The idea is to build a computed value copy that has exactly what we want to check. Computed values are magic and only put watchers on the properties that were actually read (here, the items of list read in list.slice()). The checks in the copy watcher are actually almost useless (except weird corner cases maybe) because computed values are already extremely precise.

提交回复
热议问题