美文网首页
Vue之watch出现newValue and oldValue

Vue之watch出现newValue and oldValue

作者: studentliubo | 来源:发表于2020-05-14 18:30 被阅读0次
fd: {
  handler: function (newV, old) {
   // 此处打印的结果 newV与old相同
    console.log('newV, old: ', newV, old)
  },
  deep: true
}
mounted () {
  // data from server
  this.fd = Object.assign(this.fd, data)
} 

现象:

watch基本数据类型时正常,watch Object时就会出现这种问题。

官方解释:

image.png

案例

data: {
  model: {
    title: null,
    props: {
      prop1: 1,
      prop2: 2, 
    },
  }
},
watch: {
  computedModel: {
    deep: true,
    handler(newValue, oldValue) => {
      console.log('Change: ', this.getDifference(oldValue, newValue))
    }
  }
},
computed: {
  computedModel() {
     return lodash.cloneDeep(this.model)
   }
},
methods: {
  getDifference() {
     function changes(object, base) {
       return lodash.transform(object, function(result, value, key) {
         if (!lodash.isEqual(value, base[key])) {
           result[key] = (lodash.isObject(value) && lodash.isObject(base[key])) ? changes(value, base[key]) : value
         }
       })
     }
     return changes(object, base)
   }
},

数据源

相关文章

网友评论

      本文标题:Vue之watch出现newValue and oldValue

      本文链接:https://www.haomeiwen.com/subject/oddxohtx.html