溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Vue怎么使用watch監(jiān)聽數組或對象

發(fā)布時間:2022-07-07 10:17:42 來源:億速云 閱讀:502 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹“Vue怎么使用watch監(jiān)聽數組或對象”,在日常操作中,相信很多人在Vue怎么使用watch監(jiān)聽數組或對象問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Vue怎么使用watch監(jiān)聽數組或對象”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

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

tips: 只要bet中的屬性發(fā)生變化(可被監(jiān)測到的),便會執(zhí)行handler函數;
如果想監(jiān)測具體的屬性變化,如pokerHistory變化時,才執(zhí)行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)
  }
}

到此,關于“Vue怎么使用watch監(jiān)聽數組或對象”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI