1、分别监听(基础写法)
export default {
watch: {
// 监听单个参数
param1(newVal, oldVal) {
console.log('param1 changed:', newVal, oldVal)
},
// 监听对象的属性
'obj.name'(newVal, oldVal) {
console.log('obj.name changed:', newVal, oldVal)
}
}
}
2、用对象语法(可配置选项)
export default {
watch: {
param1: {
handler(newVal, oldVal) {
console.log('param1 changed:', newVal, oldVal)
},
immediate: true, // 立即执行
deep: true // 深度监听
},
'obj.name': {
handler(newVal, oldVal) {
console.log('obj.name changed:', newVal, oldVal)
},
immediate: true
}
}
}
3、监听多个变量变化执行同一个函数
export default {
watch: {
// 方法一:使用 computed
watchParams: {
handler(newVal, oldVal) {
console.log('params changed:', newVal, oldVal)
},
immediate: true
}
},
computed: {
watchParams() {
return {
param1: this.param1,
param2: this.param2,
'obj.name': this.obj.name
}
}
}
}
4、使用 $watch(动态监听)
export default {
created() {
// 监听单个参数
this.$watch('param1', (newVal, oldVal) => {
console.log('param1 changed:', newVal, oldVal)
})
// 监听多个参数
this.$watch(
// 监听函数
() => [this.param1, this.param2, this.obj.name],
// 回调函数
(newVal, oldVal) => {
const [newParam1, newParam2, newName] = newVal
const [oldParam1, oldParam2, oldName] = oldVal
console.log('params changed:', { newVal, oldVal })
},
// 配置选项
{
immediate: true,
deep: true
}
)
}
}
5、Vue 3 的 watch 函数(组合式 API)
<script setup>
import { ref, watch } from 'vue'
const param1 = ref('')
const param2 = ref('')
const obj = ref({ name: '' })
// 监听单个参数
watch(param1, (newVal, oldVal) => {
console.log('param1 changed:', newVal, oldVal)
})
// 监听多个参数
watch(
[param1, param2, () => obj.value.name],
(newValues, oldValues) => {
const [newParam1, newParam2, newName] = newValues
const [oldParam1, oldParam2, oldName] = oldValues
console.log('multiple params changed:', { newValues, oldValues })
},
{ immediate: true, deep: true }
)
// 监听对象的某个属性
watch(
() => obj.value.name,
(newVal, oldVal) => {
console.log('obj.name changed:', newVal, oldVal)
}
)
</script>
6、watchEffect(Vue 3 自动收集依赖)
<script setup>
import { ref, watchEffect } from 'vue'
const param1 = ref('')
const param2 = ref('')
const obj = ref({ name: '' })
// 自动追踪依赖
watchEffect(() => {
console.log('params changed:', {
param1: param1.value,
param2: param2.value,
name: obj.value.name
})
})
</script>
评论