scheduler
是 Vue
的调度器,用于管理 Watcher
的更新队列。
核心功能:
- 队列管理:收集和去重
watcher
- 异步更新:通过
nextTick
批量处理 - 顺序保证:通过
id
排序确保更新顺序 - 状态维护:通过
waiting
和flushing
控制流程 - 生命周期:处理
activated
和updated
钩子
ts
// 1. 核心数据结构
const queue: Array<Watcher> = [] // watcher 队列
const activatedChildren: Array<Component> = [] // keep-alive 组件队列
let has: { [key: number]: true | undefined | null } = {} // 去重标记
let waiting = false // 等待标记
let flushing = false // 刷新标记
// 2. 核心方法:添加 watcher 到队列
function queueWatcher(watcher: Watcher) {
const id = watcher.id
// 去重检查
if (has[id] != null) return
has[id] = true
if (!flushing) {
// 正常入队
queue.push(watcher)
} else {
// 正在刷新时,按 id 顺序插入
let i = queue.length - 1
while (i > index && queue[i].id > watcher.id) i--
queue.splice(i + 1, 0, watcher)
}
// 确保只调度一次
if (!waiting) {
waiting = true
nextTick(flushSchedulerQueue)
}
}
// 3. 核心方法:刷新队列
function flushSchedulerQueue() {
flushing = true
// 排序确保:
// 1. 父组件先于子组件更新
// 2. 用户 watcher 先于渲染 watcher
queue.sort((a, b) => a.id - b.id)
// 执行队列中的 watcher
for (index = 0; index < queue.length; index++) {
watcher = queue[index]
watcher.run()
}
// 保存副本用于生命周期钩子
const activatedQueue = activatedChildren.slice()
const updatedQueue = queue.slice()
// 重置状态
resetSchedulerState()
// 调用生命周期钩子
callActivatedHooks(activatedQueue) // activated 钩子
callUpdatedHooks(updatedQueue) // updated 钩子
}