uniapp vue3 watch的使用方法
在uniapp中使用vue3的watch时,监听ref或reactive对象的具体写法是什么?比如我想监听一个对象属性的变化,是否需要使用deep选项?另外,如何在setup语法糖中正确使用watchEffect?遇到监听失效的情况应该怎么排查?
2 回复
在Vue3中,使用watch监听响应式数据变化。例如:
import { ref, watch } from 'vue'
const count = ref(0)
watch(count, (newVal, oldVal) => {
console.log(`count从${oldVal}变为${newVal}`)
})
也可以监听多个数据源:
watch([count, name], ([newCount, newName], [oldCount, oldName]) => {
// 处理变化
})
在 UniApp 中使用 Vue 3 的 watch 方法与标准 Vue 3 一致,主要用于监听响应式数据的变化。以下是常见用法:
1. 基本监听
import { ref, watch } from 'vue';
const count = ref(0);
// 监听单个 ref
watch(count, (newVal, oldVal) => {
console.log(`count 从 ${oldVal} 变为 ${newVal}`);
});
2. 监听多个源
const count = ref(0);
const name = ref('');
// 监听多个 ref
watch([count, name], ([newCount, newName], [oldCount, oldName]) => {
console.log(`count 或 name 发生变化`);
});
3. 监听 reactive 对象属性
import { reactive, watch } from 'vue';
const state = reactive({
count: 0,
user: { name: 'Tom' }
});
// 监听特定属性
watch(
() => state.count,
(newVal, oldVal) => {
console.log(`count 变化: ${oldVal} -> ${newVal}`);
}
);
// 深度监听对象
watch(
() => state.user,
(newVal, oldVal) => {
console.log('user 对象变化');
},
{ deep: true }
);
4. 立即执行
watch(
count,
(newVal) => {
console.log(`当前值: ${newVal}`);
},
{ immediate: true }
);
5. 监听器清理
const stop = watch(count, (newVal) => {
if (newVal > 10) {
stop(); // 停止监听
}
});
注意事项:
- 在 UniApp 的页面/组件卸载时,Vue 3 会自动停止监听,但手动创建的监听器建议在
onUnmounted中清理。 - 监听 reactive 对象时,默认是浅层监听,需要深度监听时添加
{ deep: true }。 - 在组合式 API 中,
watch应在setup()或<script setup>中使用。
这些方法在 UniApp 的 Vue 3 环境中完全适用,可根据实际需求选择使用。

