Watch在使用上细节确实不少。(下面代码都运行测试通过)
- 第一个参数:多种类型的入参,哪些情况必须写成getter呢?
- 第二个参数:多个数据源的监听是容易被忘记的写法,
- 第三个参数:
- immediate:明白后,可以对比watchEffect,进步可以了解内部实现中的lazy,同样lazy和computed实现更是强相关;
- flush:是重要的技术点,可以参照watchEffect,也就容易理解watchPostEffect/watchSyncEffect的语法糖api;
- onTrigger/onTrack:这两个选项和 @vue/reactivit包实现细节有很大关系,这里的代码写法比 vue2的实现优雅许多;
- 返回值watchStopHandler:是常被忽略清理的对象,对副作用域的处理可以参考 vueuse中的部分实现,学习优雅,
响应式追踪
const state = reactive({
count: 0 });
watch(() => state.count, (newValue, oldValue) => {
console.log(`${
oldValue} -> ${
newValue}`);
});
懒加载
const state = reactive({
count: 0 });
watch(() => state.count, (newValue, oldValue) => {
console.log(`${
oldValue} -> ${
newValue}`);
}, {
immediate: true });
立即执行
const state = reactive({
count: 0 });
watch(() => state.count, (newValue, oldValue) => {
console.log(`${
oldValue} -> ${
newValue}`);
}, {
immediate: true });
深度侦听
const state = reactive({
nested: {
count: 0 } });
watch(() => state.nested.count, (newValue, oldValue) => {
console.log(`${
oldValue} -> ${
newValue}`);
}, {
deep: true });
刷新时机
const state = reactive({
count: 0 });
watch(() => state.count, (newValue, oldValue) => {
console.log(`${
oldValue} -> ${
newValue}`);
}, {
flush: 'post' });
调试选项
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) });
清理回调
const state = reactive({
count: 0 });
const cleanup = () => console.log('Cleanup called');
watch(() => state.count, (newValue, oldValue) => {
console.log(`${
oldValue} -> ${
newValue}`);
}, {
onCleanup: cleanup });
停止侦听
const state = reactive({
count: 0 });
const stop = watch(() => state.count, (newValue, oldValue) => {
console.log(`${
oldValue} -> ${
newValue}`);
});
// 停止侦听
stop();
侦听多个源
const state = reactive({
count: 0, name: 'Vue' });
watch([() => state.count, () => state.name], ([newValue, oldValue], [prevCount, prevName]) => {
console.log(`${
prevCount} -> ${
newValue}, ${
prevName} -> ${
oldValue}`);
});
只执行一次
const state = reactive({
count: 0 });
watch(() => state.count, (newValue, oldValue) => {
console.log(`${
oldValue} -> ${
newValue}`);
}, {
immediate: true, once: true });