diff --git a/packages/runtime-core/src/index.ts b/packages/runtime-core/src/index.ts index e69de29..a3a2657 100644 --- a/packages/runtime-core/src/index.ts +++ b/packages/runtime-core/src/index.ts @@ -0,0 +1 @@ +export { queuePreFlushCb } from './scheduler' diff --git a/packages/runtime-core/src/scheduler.ts b/packages/runtime-core/src/scheduler.ts index 8f46835..b671ea8 100644 --- a/packages/runtime-core/src/scheduler.ts +++ b/packages/runtime-core/src/scheduler.ts @@ -1 +1,35 @@ let isFlushPending = false + +const resolvedPromise = Promise.resolve() as Promise + +let currentFlushPromise: Promise | null = null + +const pendingPreFlushCbs: Function[] = [] +export function queuePreFlushCb(cb: Function) { + queueCb(cb, pendingPreFlushCbs) +} +function queueCb(cb: Function, pendingQueue: Function[]) { + pendingQueue.push(cb) + queueFlush() +} + +function queueFlush() { + if (!isFlushPending) { + isFlushPending = true + currentFlushPromise = resolvedPromise.then(flushJobs) + } +} +function flushJobs() { + isFlushPending = false + flushPreFlushCbs() +} +export function flushPreFlushCbs() { + if (pendingPreFlushCbs.length) { + //拷贝去重,类似深拷贝 + let activePreFlushCbs = [...new Set(pendingPreFlushCbs)] + pendingPreFlushCbs.length = 0 + for (let i = 0; i < activePreFlushCbs.length; i++) { + activePreFlushCbs[i]() + } + } +} diff --git a/packages/vue/examples/reactivity/scheduler-2.html b/packages/vue/examples/reactivity/scheduler-2.html new file mode 100644 index 0000000..2cf8208 --- /dev/null +++ b/packages/vue/examples/reactivity/scheduler-2.html @@ -0,0 +1,28 @@ + + + + + Document + + + +
+ + + \ No newline at end of file diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts index 6a2f477..8fb36c5 100644 --- a/packages/vue/src/index.ts +++ b/packages/vue/src/index.ts @@ -1 +1,2 @@ export { reactive, effect, ref, computed } from '@vue/reactivity' +export { queuePreFlushCb } from '@vue/runtime-core'