美文网首页
关于watch监听数组的问题

关于watch监听数组的问题

作者: 逆流成河wsy | 来源:发表于2018-09-10 15:06 被阅读260次

    注意:在变异 (不是替换) 对象或数组时,旧值将与新值相同,因为它们的引用指向同一个对象/数组。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
            })
          }
        }
      }
    

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

    相关文章

      网友评论

          本文标题:关于watch监听数组的问题

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