vue对各种数据类型的监听方式

Vue父组件向子组件传递一个动态的值,子组件如何保持实时更新实时更新? 场景:父组件发生数据变化,动态的传递给子组件,子组件实时刷新视图

解决方法:需要在子组件watch中(监听)父组件数据的变化

在子组件中使用watch应该注意的问题:

1.watch监听普通类型的数据:

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

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)  
        }  
      }  
    },  
    deep: true  
  }  
}

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)  
  }  
}

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

经验分享 程序员 微信小程序 职场和发展