前言
在vue開發的過程中發現一個問題:改變vue.$data中對象的屬性,watch是觀測不到變化,但其實對象的屬性是有變化的。這……,有點難以置信!
正文
<template>
<div>
<dl>name: {{option.name}}</dl>
<dl>age: {{option.age}}</dl>
<dl>
<button @click="updateAgeTo25">update age with 25</button>
</dl>
</div>
</template>
<script>
export default {
data () {
return {
option: {
name: "isaac",
age: 24
}
}
},
watch: {
option(val) {
console.log(val)
}
},
methods: {
updateAgeTo25() {
this.option.age = 25
}
}
}
</script>
image
image
如結果所示,option.age已經更新,但是watch中的option函數并沒有被觸發。
vue的watch鉤子會那么雞肋?我是不信的了。
深層watch
...
watch: {
option: {
handler(newVal) {
console.log(newVal);
},
deep: true,
immediate: true
}
},
...
需要深層watch就需要開啟deep
屬性
image
image
如結果所示。
另外,你會發現,在age沒有變化前也是有打印出option,這是因為開啟immediate
屬性,設定為true
,
該回調將會在偵聽開始之后被立即調用