第一步
watchEffect 函数是当依赖的值变化后,自动指定该函数中的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import { ReactiveEffect } from './effect'; import { isFunction, isObject } from '@vue/shared'; import { isReactive } from './reactive'; import { isRef } from './ref';
export function watch(source, cb, options = {} as any) { return doWatch(source, cb, options); }
...
export function watchEffect(source, options = {} as any) { return doWatch(source, null, options); }
function doWatch(source, cb, { deep, immediate }) { ...
let oldValue; const job = () => { if (cb) { const newValue = effect.run(); cb(newValue, oldValue); oldValue = newValue; } else { effect.run(); } };
const effect = new ReactiveEffect(getter, job);
if (cb) { if (immediate) { job(); } else { oldValue = effect.run(); } } else { effect.run(); } }
|