$watch中的oldvalue和newValue

vue中提供了$watch的方法来作对象变化的监听,并且在callback中会返回两个对象,分别是oldValue和newValue.
顾名思义,这两个对象就是对象发生变化先后的值。
可是在使用过程当中我发现这两个值并不老是预期的。html

定义data的值vue

data: {
    arr: [{
      name: '笨笨',
      address: '上海'
    }, {
      name: '笨笨熊',
      address: '北京'
    }],
    obj: {
      name: '呆呆',
      address: '苏州'
    },
    str: '哈哈哈'
  }

定义watchgit

watch: {
    arr: function(newValue, oldValue) {
      console.log(newValue, oldValue)
      console.log(JSON.stringify(oldValue) === JSON.stringify(newValue))
    },
    obj: function(newValue, oldValue) {
      console.log(newValue, oldValue)
      console.log(JSON.stringify(oldValue) === JSON.stringify(newValue))
    },
    str: function(newValue, oldValue) {
      console.log(newValue, oldValue)
      console.log(JSON.stringify(oldValue) === JSON.stringify(newValue))
    },
  }

定义事件触发github

methods: {
    test() {
      this.arr.push({
        name: 9
      })
      this.$set(this.obj, 'i', 0)
      this.str = ''
    },
    test1() {
      this.arr = [{
        name: '000'
      }]
      this.obj = {
        name: 999
      }
      this.str = '123'
    }
  }

测试结果为segmentfault

对数组进行push操做和对Obj进行$set操做,虽然均可能触发watch事件,可是在callback返回的结果中,oldValue和newValue相同。字符串对象如预期返回数组

在对数组和Obj统一进行赋值操做时,watch触发而且oldValue和newValue如预期返回测试

关于watch的其余测试能够参考我以前的文章
vue中正确的使用watch进行监听this

测试地址(测试时请打开控制台)
https://zuank.github.io/notes...code

相关文章
相关标签/搜索