watchEffect 实现

第一步

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) {
// watchEffect 也是基于 doWatch 实现的
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();
// -----------------------------新增结束-----------------------------
}
}