关于watch监听数组的问题

注意:在变异 (不是替换) 对象或数组时,旧值将与新值相同,因为它们的引用指向同一个对象/数组。Vue 不会保留变异之前值的副本。
这样是可以监听到的

  mounted() {
    this.$service.enableInvoiceOrders(this.$route.params.orderType).then(res => {
      console.log(res)
      if (res.code == 0) {
        // watch监听数组先处理初始值 再赋值 最后再监听
//我的理解也就是会监听两次一次判断是否数组 一次赋值是否变异
        res.data.records.forEach(item => {
          item.isSelectItem = false
        })
        this.orderArr = res.data.records
        // 相当于变异了
        // this.orderArr.forEach(item => {
        //   item.isSelectItem = false
        // })
      }
    })
  },
 watch: {
    orderArr: {
      deep: true,
      handler(val, oldVal) {
        console.log(val, '==数据==')
        this.ischeckAll = val.every(item => {
          return item.isSelectItem
        })
      }
    }
  }

这样监听不到

  mounted() {
    this.$service.enableInvoiceOrders(this.$route.params.orderType).then(res => {
      console.log(res)
      if (res.code == 0) {
        this.orderArr = res.data.records
        // 相当于变异了
        this.orderArr.forEach(item => {
           item.isSelectItem = false
        })
      }
    })
  },
 watch: {
    orderArr: {
      deep: true,
      handler(val, oldVal) {
        console.log(val, '==数据==')
        this.ischeckAll = val.every(item => {
          return item.isSelectItem
        })
      }
    }
  }

关于深度监听 如果数组不深度监听 相当于只监听一个数组的地址
注意:最好不要监听数组或者对象 这样内存消耗比较大

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。