美文网首页
用watch兼听对象时,oldValue与newValue值相同

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

作者: 努力study代码的小哪吒 | 来源:发表于2022-04-26 11:25 被阅读0次
    当我们需要监听多个字段值的变化时,可以直接创建个对象,然后去直接监听这个对象,这样任何一个属性发生变化时,我们都可以感受到(但是我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))
        }
      }
    

    相关文章

      网友评论

          本文标题:用watch兼听对象时,oldValue与newValue值相同

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