Vue父組件向子組件傳遞一個動態的值,子組件如何保持實時更新實時更新?


原文:https://blog.csdn.net/zhouweixue_vivi/article/details/78550738

 

 

        最近用vue做一個新項目,經歷了各種折磨,每次遇到問題都想大喊,格勞資上JQuery,氮素肯定是不行的,今天遇到一個小問題,Vue父組件向子組件傳遞一個動態的值,子組件只能獲取初始值,不能實時更新?

這就有點折磨人了,設想的是,父組件發生變化獲取數據,動態傳遞給子組件,子組件實時刷新視圖。vue視圖是數據驅動的嘛,這設想就是完美而合理的了吧。可就是不行!!!!

  請教前輩,支個招讓用vuex,可就是個小功能能,有點殺雞用牛刀啊,又去查了查文檔,找了找資料。原來需要在子組件watch(監聽)父組件數據的變化。

我就這樣使用watchl啦,

 
data() {
    return {
        frontPoints: 0
    }
 
},
watch: {
    frontPoints(newValue, oldValue) {
        console.log(newValue)
    }
}        
咦?又出幺蛾子了,完全監聽不到嘛!!!

繼續查文檔,好嘛,原來這種方式只能watch基礎類型的變量,我傳遞的是個object啊,代碼,真的處處是坑。。。

為了防止將來繼續掉坑,做個總結吧

1、普通watch   

如上所示,用過vue的都應該挺熟悉的

 

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   } }
tips: 只要bet中的屬性發生變化(可被監測到的),便會執行handler函數;
如果想監測具體的屬性變化,如pokerHistory變化時,才執行handler函數,則可以利用計算屬性computed做中間層。
事例如下:

4、對象的具體屬性watch(活用computed)

 

data () {
  return {
    bet: {       pokerState:
53,
      pokerHistory:
'local'     } } }, computed: {
  pokerHistory() {
    
return this.bet.pokerHistory   } }, watch: {   pokerHistory(newValue, oldValue) {
    console.log(newValue)
  } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM