導讀
使用 Vue 中的 watch 方法監聽對象,設置 deep:true 可以進行深度監聽,當對象中的屬性發生變化時,會調用 handler 方法。
<template>
<div>
<input v-model="test.text">
</div>
</template>
<script>
export default {
data () {
return {
test: {
text: ''
}
}
},
watch:{
test: {
deep: true,
handler: function (newVal,oldVal){
console.log('newValue', newVal);
console.log('oldValue', oldVal.text);
}
}
}
}
</script>
如果需要只監聽對象中某一屬性的變化,watch 也能實現,另外也可以結合使用計算屬性 computed 來對此進行監聽。
<script>
export default {
data () {
return {
test: {
text1: '',
text2: ''
}
}
},
watch:{
'test.text1': {
deep: true,
handler: function (newVal,oldVal){
// code
}
}
}
}
</script>
以下是結合計算屬性對某一對象的單一屬性實現監聽的方法:
<script>
export default {
data () {
return {
test: {
text1: '',
text2: ''
}
}
},
computed:{
testText1 () {
return this.test.text1
}
},
watch:{
testText1: {
dosomething (newVal,oldVal){
// code
}
}
}
}
</script>
寫在最后
如果文中有什么錯誤,歡迎大家指正,我們不怕錯,就怕錯不知。感謝。
