Usage scenarios and differences between computed and watch

computed

Computed is suitable for dynamically calculating the attribute value in data. Return must be added. The attribute in data cannot be assigned. When there is no change, it will be read from the cache first.
Usage scenario: When a value is affected by multiple attributes

 computed: {
    
    
    btnText(){
    
    
      return this.totalCount !== 0 ? `${
      
      this.totalCount}s`: "获取验证码"
    }
  } 

Sometimes you can also use get and set

computed: {
    
    
  list: {
    
    
    get() {
    
    
        return this.$store.state.list
    },
    set(value) {
    
    
        this.$store.commit('updateList', value)
    }
  }
}

watch

Watch is to monitor the change of the value in data. When the attribute in data changes, the function in watch will be executed. There are two parameters, the former is newVal and the latter is oldVal. When monitoring the changes of reference type data, you need to perform deep monitoring ( handler + deep for deep monitoring. Immediate: true when the page is loaded for the first time, do a monitoring.
Usage scenario: When a data change affects multiple data

 watch: {
    
    
 	//a,b,c,d为data里的数据名
    a(newVal, oldVal) {
    
    
      	console.log(newVal, oldVal)
    },
    // 方法名
    b: 'someMethod',
    c: {
    
    
      handler(newVal, oldVal) {
    
    },
      deep: true // 该回调会在任何被侦听的对象的 property 改变时被调用,不论其被嵌套多深,一般用于监听对象
    },
    d: {
    
    
      handler: 'someMethod',
      immediate: true    // 该回调将会在侦听开始之后被立即调用
    },
},

How to monitor changes in multiple values?

Watch needs to be used in conjunction with computed

computed: {
    
    
   info() {
    
    
      const {
    
     password, userCode } = this
      return {
    
    
          password,
          userCode
      }
   },
   //直接对一个对象尽行深度接听多个属性值
   obj(){
    
    
       return JSON.parse(JSON.stringify(object))
   }
   
},
watch:{
    
    
    info:{
    
    
       handler: function(newval , oldval) {
    
    
          if(newval.password && newval.userCode){
    
    
            this.sign = true
          }else{
    
    
            this.sign = false
          }
       },
       deep:true
   },
   obj:{
    
    
   	   handler: function(newval , oldval) {
    
     xx },
       deep:true
   }
}

Guess you like

Origin blog.csdn.net/m0_48076809/article/details/106885948