Vue父组件向子组件传递一个动态的值,子组件如何保持实时更新实时更新?

场景:父组件发生数据变化,动态的传递给子组件,子组件实时刷新视图

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

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

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

  1. data() {  
  2.     return {  
  3.         frontPoints: 0      
  4.     }  
  5. },  
  6. watch: {  
  7.     frontPoints(newValue, oldValue) {  
  8.         console.log(newValue)  
  9.     }  
  10. }  

2.watch监听数组类型 的数据

  1. data() {  
  2.     return {  
  3.         winChips: new Array(11).fill(0)     
  4.     }  
  5. },  
  6. watch: {  
  7.   winChips: {  
  8.     handler(newValue, oldValue) {  
  9.       for (let i = 0; i < newValue.length; i++) {  
  10.         if (oldValue[i] != newValue[i]) {  
  11.           console.log(newValue)  
  12.         }  
  13.       }  
  14.     },  
  15.     deep: true  
  16.   }  
  17. }  
3.watch监听对象类型的数据

  1. data() {  
  2.   return {  
  3.     bet: {  
  4.       pokerState: 53,  
  5.       pokerHistory: 'local'  
  6.     }     
  7.     }  
  8. },  
  9. watch: {  
  10.   bet: {  
  11.     handler(newValue, oldValue) {  
  12.       console.log(newValue)  
  13.     },  
  14.     deep: true  
  15.   }  
  16. }  

4.watch监听对象的具体属性:(结合computed)

  1. data() {  
  2.   return {  
  3.     bet: {  
  4.       pokerState: 53,  
  5.       pokerHistory: 'local'  
  6.     }     
  7.     }  
  8. },  
  9. computed: {  
  10.   pokerHistory() {  
  11.     return this.bet.pokerHistory  
  12.   }  
  13. },  
  14. watch: {  
  15.   pokerHistory(newValue, oldValue) {  
  16.     console.log(newValue)  
  17.   }  
  18. }  
tips: 只要bet中的属性发生变化(可被监测到的),便会执行handler函数;
如果想监测具体的属性变化,如pokerHistory变化时,才执行handler函数,则可以利用计算属性computed做中间层。
事例如下:

猜你喜欢

转载自blog.csdn.net/weixin_38098192/article/details/80447867