什么是watch?
一个对象,键是需要观察的表达式,值是对应回调函数。值也可以是方法名,或者包含选项的对象。Vue 实例将会在实例化时调用 $watch()
,遍历 watch 对象的每一个属性。
类型:{ [key: string]: string | Function | Object | Array }
测试公共代码如下:
<template>
<div>
<input type="text" v-model="watchTextOne"/><br><br>
<input type="text" v-model="watchTextTwo"/><br><br>
<input type="text" v-model="watchTextThree"/><br><br>
<input type="text" v-model="watchTextFour.name"/><br><br>
<input type="text" v-model="watchTextFour.age"/><br><br>
<input type="text" v-model="watchTextFour.feature"/><br><br>
<input type="text" v-model="watchTextFour.feature[0]"/>
</div>
</template>
<script>
export default {
data () {
return {
watchTextOne: '',
watchTextTwo: '',
watchTextThree: '',
watchTextFour: {
name: 'fx',
age: 18,
feature: ['smart', 'great']
}
}
},
}
</script>
第一种方式:
watch: {
// 第一种watch监听方式
watchTextOne (newVal, oldVal) {
console.log('watchTextOne新值:', newVal)
console.log('watchTextOne旧值:', oldVal)
},
},
第二种方式:
watch: {
// 第二种watch监听方式,写一个监听处理函数
watchTextTwo: 'watchTextTwoFn',
}|
methods: {
watchTextTwoFn (newVal, oldVal) {
console.log('watchTextTwo新值:', newVal)
console.log('watchTextTwo旧值:', oldVal)
},
},
以上两种方式使用watch时有一个特点,就是当值第一次绑定的时候,不会执行监听函数,只有值发生改变才会执行。
如果我们需要在最初绑定值的时候也执行函数,则就需要用到immediate属性。
比如当父组件向子组件动态传值时,子组件props首次获取到父组件传来的默认值时,也需要执行函数,此时就需要将immediate设为true。
第三种方式:
watchTextThree: {
handler (newVal, oldVal) {
console.log('watchTextThree新值:', newVal)
console.log('watchTextThree旧值:', oldVal)
},
immediate: true // immediate表示在watch中首次绑定的时候,是否执行handler
},
当需要监听一个对象的改变时,普通的watch方法无法监听到对象内部属性的改变,只有data中的数据才能够监听到变化,此时就需要deep属性对对象进行深度监听。
watchTextFour: {
handler (newVal, oldVal) {
console.log('watchTextFour新值:', newVal)
console.log('watchTextFour旧值:', oldVal)
},
deep: true // 此时会给watchTextFour的所有属性都加上这个监听器,当对象属性较多时,每个属性值的变化都会执行handler。
},
如果只需要监听对象中的一个属性值,则可以做以下优化:使用字符串的形式监听对象属性:
'watchTextFour.age': {
handler (newVal, oldVal) {
console.log('watchTextFour.age新值:', newVal)
console.log('watchTextFour.age旧值:', oldVal)
},
deep: true
},