vue3中watch(监听)的五种情况
在Vue 3中,watch用于观察Vue组件中数据的变化,并执行相应的函数来响应这些变化。以下是watch的五种常见情况和相应的代码示例:
- 观察响应式引用:
import { watch, ref } from 'vue';
const counter = ref(0);
watch(counter, (newValue, oldValue) => {
console.log(`The new counter value is: ${newValue}, old value was: ${oldValue}`);
});
// 更改counter的值
counter.value++;
- 观察响应式对象中的属性:
import { reactive, watch } from 'vue';
const state = reactive({
count: 0,
name: 'Vue'
});
watch(() => state.count, (newValue, oldValue) => {
console.log(`state.count changed from ${oldValue} to ${newValue}`);
});
// 更改state.count的值
state.count++;
- 直接传入响应式引用或函数,并监听其变化:
import { watch, ref } from 'vue';
const counter = ref(0);
watch(counter, (newValue, oldValue) => {
console.log(`The new counter value is: ${newValue}, old value was: ${oldValue}`);
});
// 更改counter的值
counter.value++;
- 使用deep配置来深度观察一个对象:
import { reactive, watch } from 'vue';
const state = reactive({
count: 0,
nested: { value: 'Nested value' }
});
watch(
() => state.nested,
(newValue, oldValue) => {
console.log('Nested property changed:', newValue, oldValue);
},
{
deep: true
}
);
// 更改嵌套对象的属性
state.nested.value = 'Updated nested value';
- 使用immediate配置来立即执行watch的回调函数:
import { watch, ref } from 'vue';
const counter = ref(0);
watch(counter, (newValue, oldValue) => {
console.log(`The new counter value is: ${newValue}, old value was: ${oldValue}`);
}, {
immediate: true
});
// 组件已挂载时,counter的值已经被观察
以上代码示例展示了Vue 3中watch的基本用法,包括如何观察响应式数据的变化、如何进行深度观察以及如何在组件初始化时立即执行watch的回调函数。
评论已关闭