1. 程式人生 > >Vue父元件向子元件傳遞一個動態的值,子元件如何保持實時更新實時更新?

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.     returnthis.bet.pokerHistory  
  12.   }  
  13. },  
  14. watch: {  
  15.   pokerHistory(newValue, oldValue) {  
  16.     console.log(newValue)  
  17.   }  
  18. }  
tips: 只要bet中的屬性發生變化(可被監測到的),便會執行handler函式;
如果想監測具體的屬性變化,如pokerHistory變化時,才執行handler函式,則可以利用計算屬性computed做中間層。
事例如下: