在 Vue 2 和 Vue 3 中,watch 用于监听数据的变化并执行相应的逻辑。虽然两者的核心功能相同,但在语法和使用方式上有一些区别。以下是 Vue 2 和 Vue 3 中使用 watch 的详细说明:
Vue 2 中的 watch
在 Vue 2 中,watch 是通过选项式 API 实现的,通常在组件的 watch 选项中定义。
【基本用法】
export default {data() {return {message: 'Hello Vue 2',count: 0,};},watch: {// 监听 message 的变化message(newVal, oldVal) {console.log('message changed:', newVal, oldVal);},// 监听 count 的变化count(newVal, oldVal) {console.log('count changed:', newVal, oldVal);},},
};
【监听对象属性】
如果需要监听对象的某个属性,可以使用字符串形式的键名:
export default {data() {return {user: {name: 'Alice',age: 25,},};},watch: {'user.name'(newVal, oldVal) {console.log('user.name changed:', newVal, oldVal);},},
};
【深度监听】
如果需要监听对象或数组内部的变化,可以设置 deep: true:
export default {data() {return {user: {name: 'Alice',age: 25,},};},watch: {user: {handler(newVal, oldVal) {console.log('user changed:', newVal, oldVal);},deep: true, // 深度监听},},
};
【立即执行】
如果需要监听器在创建时立即执行一次,可以设置 immediate: true:
export default {data() {return {message: 'Hello Vue 2',};},watch: {message: {handler(newVal, oldVal) {console.log('message changed:', newVal, oldVal);},immediate: true, // 立即执行},},
};
Vue3中的watch
在 Vue 3 中,watch 是通过 Composition API 实现的,使用 watch 函数来定义监听器。
【基本用法】
import { ref, watch } from 'vue';export default {setup() {const message = ref('Hello Vue 3');const count = ref(0);// 监听 message 的变化watch(message, (newVal, oldVal) => {console.log('message changed:', newVal, oldVal);});// 监听 count 的变化watch(count, (newVal, oldVal) => {console.log('count changed:', newVal, oldVal);});return {message,count,};},
};
【监听多个数据】
import { ref, watch } from 'vue';export default {setup() {const firstName = ref('Alice');const lastName = ref('Smith');// 监听 firstName 和 lastName 的变化watch([firstName, lastName], ([newFirstName, newLastName], [oldFirstName, oldLastName]) => {console.log('firstName or lastName changed:', newFirstName, newLastName);});return {firstName,lastName,};},
};
【监听对象属性】
import { ref, watch } from 'vue';export default {setup() {const user = ref({name: 'Alice',age: 25,});// 监听 user.name 的变化watch(() => user.value.name,(newVal, oldVal) => {console.log('user.name changed:', newVal, oldVal);});return {user,};},
};
【深度监听】
在 Vue 3 中,默认情况下 watch 是浅层的。如果需要深度监听,可以设置 { deep: true }:
import { ref, watch } from 'vue';export default {setup() {const user = ref({name: 'Alice',age: 25,});// 深度监听 user 对象watch(user,(newVal, oldVal) => {console.log('user changed:', newVal, oldVal);},{ deep: true });return {user,};},
};
【立即执行】
如果需要监听器在创建时立即执行一次,可以设置 { immediate: true }:
import { ref, watch } from 'vue';export default {setup() {const message = ref('Hello Vue 3');// 立即执行监听器watch(message,(newVal, oldVal) => {console.log('message changed:', newVal, oldVal);},{ immediate: true });return {message,};},
};