Vue父元件向子元件傳遞一個動態的值,子元件如何保持實時更新實時更新?
阿新 • • 發佈:2019-01-23
場景:父元件發生資料變化,動態的傳遞給子元件,子元件實時重新整理檢視
解決方法:需要在子元件watch中(監聽)父元件資料的變化
在子元件中使用watch應該注意的問題:
1.watch監聽普通型別的資料:
- data() {
- return {
- frontPoints: 0
- }
- },
- watch: {
- frontPoints(newValue, oldValue) {
- console.log(newValue)
- }
- }
2.watch監聽陣列型別 的資料
- data() {
- return {
- winChips: new
- }
- },
- watch: {
- winChips: {
- handler(newValue, oldValue) {
- for (let i = 0; i < newValue.length; i++) {
- if (oldValue[i] != newValue[i]) {
- console.log(newValue)
- }
- }
- },
- deep: true
- }
- }
- 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() {
- returnthis.bet.pokerHistory
- }
- },
- watch: {
- pokerHistory(newValue, oldValue) {
- console.log(newValue)
- }
- }
tips: 只要bet中的屬性發生變化(可被監測到的),便會執行handler函式;
如果想監測具體的屬性變化,如pokerHistory變化時,才執行handler函式,則可以利用計算屬性computed做中間層。
事例如下: