用watch兼听对象时,oldValue与newValue值相同的问题

当我们需要监听多个字段值的变化时,可以直接创建个对象,然后去直接监听这个对象,这样任何一个属性发生变化时,我们都可以感受到(但是我console之后,发现oldVal,和newVal值相同)

数据定义(代码中getPrice()是对象发生变化时,去走的方法,这里替换成你自己需要的即可)

data () {
    return {
        priceForm: {
          activityId: '',
          terminalType: '',
          authenType: '',
          chargeType: '',
          currentTime: '',
          memberLevel: ''
        },
       timer: null
    }
}
watch: {
    priceForm: {
      handler: function (newVal, oldVal) {
        console.log('newVal', newVal, 'oldVal', oldVal)
        this.getPrice()
      },
      deep: true
    }
}
有上述问题的之后我们就来想办法解决他 =>添加computed计算属性即可
watch: {
    priceFormData: {
      handler: function (newVal, oldVal) {
        console.log('newVal', newVal)
        console.log('oldVal', oldVal)
        this.getPrice()
      },
      deep: true
    }
  },
  computed: {
    priceFormData () {
      return JSON.parse(JSON.stringify(this.priceForm))
    }
  }
这样之后又发现了个问题,因为每一个属性的改变一个一个的,这样我初始化页面的时候改变一次就会调一次接口,但是其实初始化的时候我调用一次接口就可以了=>所以添加了一个timeout
watch: {
    priceFormData: {
      handler: function (newVal, oldVal) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          this.getPrice()
        }, 1000)
      },
      deep: true
    }
  },
  computed: {
    priceFormData () {
      return JSON.parse(JSON.stringify(this.priceForm))
    }
  }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容