导读
使用 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>
写在最后
如果文中有什么错误,欢迎大家指正,我们不怕错,就怕错不知。感谢。