wip: fix watch simple effect usage

This commit is contained in:
Evan You 2019-08-19 14:44:52 -04:00
parent 36ab2ab980
commit 145bf98840
2 changed files with 25 additions and 11 deletions

View File

@ -77,9 +77,6 @@ function doWatch(
| null, | null,
{ lazy, deep, flush, onTrack, onTrigger }: WatchOptions = EMPTY_OBJ { lazy, deep, flush, onTrack, onTrigger }: WatchOptions = EMPTY_OBJ
): StopHandle { ): StopHandle {
const scheduler =
flush === 'sync' ? invoke : flush === 'pre' ? queueJob : queuePostFlushCb
const baseGetter = isArray(source) const baseGetter = isArray(source)
? () => source.map(s => (isRef(s) ? s.value : s())) ? () => source.map(s => (isRef(s) ? s.value : s()))
: isRef(source) : isRef(source)
@ -111,17 +108,24 @@ function doWatch(
} }
: void 0 : void 0
const scheduler =
flush === 'sync' ? invoke : flush === 'pre' ? queueJob : queuePostFlushCb
const runner = effect(getter, { const runner = effect(getter, {
lazy: true, lazy: true,
// so it runs before component update effects in pre flush mode // so it runs before component update effects in pre flush mode
computed: true, computed: true,
onTrack, onTrack,
onTrigger, onTrigger,
scheduler: applyCb ? () => scheduler(applyCb) : void 0 scheduler: applyCb ? () => scheduler(applyCb) : scheduler
}) })
if (!lazy) { if (!lazy) {
applyCb && scheduler(applyCb) if (applyCb) {
scheduler(applyCb)
} else {
scheduler(runner)
}
} else { } else {
oldValue = runner() oldValue = runner()
} }

View File

@ -8,22 +8,32 @@ export function nextTick(fn?: () => void): Promise<void> {
return fn ? p.then(fn) : p return fn ? p.then(fn) : p
} }
export function queueJob(job: () => void, onError?: (err: Error) => void) { type ErrorHandler = (err: Error) => void
export function queueJob(job: () => void, onError?: ErrorHandler) {
if (queue.indexOf(job) === -1) { if (queue.indexOf(job) === -1) {
queue.push(job) queue.push(job)
if (!isFlushing) { queueFlush(onError)
const p = nextTick(flushJobs)
if (onError) p.catch(onError)
}
} }
} }
export function queuePostFlushCb(cb: Function | Function[]) { export function queuePostFlushCb(
cb: Function | Function[],
onError?: ErrorHandler
) {
if (Array.isArray(cb)) { if (Array.isArray(cb)) {
postFlushCbs.push.apply(postFlushCbs, cb) postFlushCbs.push.apply(postFlushCbs, cb)
} else { } else {
postFlushCbs.push(cb) postFlushCbs.push(cb)
} }
queueFlush(onError)
}
function queueFlush(onError?: ErrorHandler) {
if (!isFlushing) {
const p = nextTick(flushJobs)
if (onError) p.catch(onError)
}
} }
const dedupe = (cbs: Function[]): Function[] => Array.from(new Set(cbs)) const dedupe = (cbs: Function[]): Function[] => Array.from(new Set(cbs))