Skip to content

Vue3 Watch的使用

2024-08-19

Watch在使用上细节确实不少。(下面代码都运行测试通过)

在这里插入图片描述在这里插入图片描述

  1. 第一个参数:多种类型的入参,哪些情况必须写成getter呢?
  2. 第二个参数:多个数据源的监听是容易被忘记的写法,
  3. 第三个参数:
  • immediate:明白后,可以对比watchEffect,进步可以了解内部实现中的lazy,同样lazy和computed实现更是强相关;
  • flush:是重要的技术点,可以参照watchEffect,也就容易理解watchPostEffect/watchSyncEffect的语法糖api;
  • onTrigger/onTrack:这两个选项和 @vue/reactivit包实现细节有很大关系,这里的代码写法比 vue2的实现优雅许多;
  • 返回值watchStopHandler:是常被忽略清理的对象,对副作用域的处理可以参考 vueuse中的部分实现,学习优雅,

1. 响应式追踪

javascript
const state = reactive({ count: 0 });
watch(() => state.count, (newValue, oldValue) => {
  console.log(`${oldValue} -> ${newValue}`);
});

2. 懒加载

javascript
const state = reactive({ count: 0 });
watch(() => state.count, (newValue, oldValue) => {
  console.log(`${oldValue} -> ${newValue}`);
}, { immediate: true });

3. 立即执行

javascript
const state = reactive({ count: 0 });
watch(() => state.count, (newValue, oldValue) => {
  console.log(`${oldValue} -> ${newValue}`);
}, { immediate: true });

4. 深度侦听

javascript
const state = reactive({ nested: { count: 0 } });
watch(() => state.nested.count, (newValue, oldValue) => {
  console.log(`${oldValue} -> ${newValue}`);
}, { deep: true });

5. 刷新时机

javascript
const state = reactive({ count: 0 });
watch(() => state.count, (newValue, oldValue) => {
  console.log(`${oldValue} -> ${newValue}`);
}, { flush: 'post' });

6. 调试选项

javascript
const state = reactive({ count: 0 });
watch(() => state.count, (newValue, oldValue) => {
  console.log(`${oldValue} -> ${newValue}`);
}, { onTrack: (e) => console.log('Tracked:', e), onTrigger: (e) => console.log('Triggered:', e) });

7. 清理回调

javascript
const state = reactive({ count: 0 });
const cleanup = () => console.log('Cleanup called');
watch(() => state.count, (newValue, oldValue) => {
  console.log(`${oldValue} -> ${newValue}`);
}, { onCleanup: cleanup });

8. 停止侦听

javascript
const state = reactive({ count: 0 });
const stop = watch(() => state.count, (newValue, oldValue) => {
  console.log(`${oldValue} -> ${newValue}`);
});
// 停止侦听
stop();

9. 侦听多个源

javascript
const state = reactive({ count: 0, name: 'Vue' });
watch([() => state.count, () => state.name], ([newValue, oldValue], [prevCount, prevName]) => {
  console.log(`${prevCount} -> ${newValue}, ${prevName} -> ${oldValue}`);
});

10. 只执行一次

javascript
const state = reactive({ count: 0 });
watch(() => state.count, (newValue, oldValue) => {
  console.log(`${oldValue} -> ${newValue}`);
}, { immediate: true, once: true });

花海相伴