zoukankan      html  css  js  c++  java
  • watch监听(数组或者对象)

    handler:监听数组或对象的属性时用到的方法

    deep:深度监听,为了发现对象内部值的变化,可以在选项参数中指定 deep:true 。注意监听数组的变动不需要这么做。

    immediate: 在选项参数中指定 immediate: true 将立即以表达式的当前值触发回调

    tips: 只要bet中的属性发生变化(可被监测到的),便会执行handler函数;如果想监测具体的属性变化,如pokerHistory变化时,才执行handler函数,则可以利用计算属性computed做中间层。

    1、普通的watch
    按 Ctrl+C 复制代码

    data() {
    return {
      frontPoints: 0
    }
    },
    watch: {
    frontPoints(newValue, oldValue) {
      console.log(newValue)
    }
    }


    按 Ctrl+C 复制代码
    2、数组的watch
    复制代码
    data() {
     return {
       winChips: new Array(11).fill(0)
     }
    },
    watch: {
      winChips: {
     handler(newValue, oldValue) {
       for (let i = 0; i < newValue.length; i++) {
      if (oldValue[i] != newValue[i]) {
          console.log(newValue)        
         }
      }
       }, 
      }
    }
    复制代码

    3、对象的watch

    复制代码
    data() {
      return {
        bet: {
          pokerState: 53,
          pokerHistory: 'local'
        }
     }
    },
    watch: {
      bet: {
        handler(newValue, oldValue) {
          console.log(newValue)    
    },
        deep: true
      }
    }
    复制代码

    4、对象具体属性的watch[活用computed]

    复制代码
    data() {
      return {
        bet: {
          pokerState: 53,
          pokerHistory: 'local'
        } 
      }
    },
    computed: {
      pokerHistory() {
        return this.bet.pokerHistory
      }
    },
    watch: {
      pokerHistory(newValue, oldValue) {
        console.log(newValue)
      }
    }
    复制代码
    5、watch和computed各自处理的数据关系场景不同

    watch擅长处理的场景:一个数据影响多个数据
    computed擅长处理的场景:一个数据受多个数据影响

    6、method和computed触发条件不同
    computed只提供了缓存的值,而没有重新计算
    只有符合:1.存在依赖型数据 2.依赖型数据发生改变这两个条件,computed才会重新计算。
    而methods下的数据,是每次都会进行计算的

  • 相关阅读:
    当···时发生了什么?
    数据存储-3、数据库分库分表思路
    数据存储-2、反模式设计
    数据存储-1、MySQL 索引使用的注意事项
    锁机制-4、synchronized 与 lock 的区别
    锁机制-3、synchronize 实现原理
    锁机制-1、乐观锁与悲观锁以及乐观锁的一种实现方式
    线程-11、线程的生命周期
    线程-10、线程池的几种方式
    线程-9、线程池的实现原理
  • 原文地址:https://www.cnblogs.com/fgwh-y/p/11211187.html
Copyright © 2011-2022 走看看