vue 中 watch如何監聽陣列或物件中的某個值?

小鹿仔發表於2020-11-19

使用watch監聽陣列或物件時, 發現返回的新舊值是一樣的, 官方文件給出了答案 :
在這裡插入圖片描述
這需要使用到 this.$set方法 , 它接受三個引數 : (object / array , properyName / index , value) ,
看下例項 :
在 data中命名一個物件 a , 一個陣列 b :

data () {
	retutn {
		a : {name : 'lily', age : 18} ,
		b : [
			{name : '小明' , age : 14} ,
			{name : '小紅' , age : 15}
		]
	}
} , 

在methods中對 a , b 進行操作 :

methods : {
	set() {
		this.$set(a , 'age' , 20);
		this.$set(b, 1 , {name : '小紅' , age : 16} ;
	}
}

在computed監聽新變數 , 一定要用JSON.parse 和 JSON.stringify 轉化一下, 不然watch監聽時返回的新舊值還是一樣的 .

computed : {
	newA : function () {
		return JSON.parse(JSON.stringify(this.a))
	} , 
	newB : function () {
		return JSON.parse(JSON.stringify(this.b))
	}
}

watch監聽 , handler函式的兩種寫法都是可以的, 但是不能使用箭頭函式 .

watch : {
	newA : {
		handler : function (newVal, oldVal) {
			console.log(newVal,oldVal)
		},
		immediate : true //初始化頁面後立即監聽
	} , 
	newB : {
		handler (newVal , oldVal) {
			console.log(newVal , oldVal)
		} ,
		immediate : true
	}
	
}

觸發set方法後 , 最後列印的結果 :
在這裡插入圖片描述
完結 , 撒花✿✿ヽ(°▽°)ノ✿

相關文章