← 返回完整题库
vue.js困难

说说Vue 页面渲染流程

参考答案

完整链路

new Vue(options)
→ _init:initLifecycle → initEvents → initRender → beforeCreate
→ initInjections → initState(props/methods/data/computed/watch)→ initProvide → created
→ $mount(el)
→ mountComponent:callHook('beforeMount') → new Watcher(vm, updateComponent, noop, {before})
→ updateComponent = () => { vm._update(vm._render(), hydrating) }
→ _render():执行 render 函数 → VNode(含 normalize、指令、插槽处理)
→ _update(vnode):vm.__patch__(prevVnode, vnode)
→ patch:createElm 递归 → 创建真实 DOM → 插入父节点 → 触发指令的 inserted 钩子
→ callHook('mounted')

各阶段在做什么

| 阶段 | 关键动作 |
|---|---|
| initState | data 转响应式、props 代理、computed 定义、watch 注册 |
| beforeMount | 渲染函数已编译,$el 换成真实模板(Vue 2 的 $el 从占位元素换成 render 结果) |
| render | 生成 VNode 树,期间完成依赖收集 |
| patch(首次) | createElm 递归:创建元素、设置 attrs/props/class/style、绑定事件、递归子节点、处理组件(createComponent → 子组件 init → $mount) |
| mounted | 整棵子树挂载完成,DOM 可访问,$refs 可用 |

更新时

数据变化 → dep.notify → watcher.update → queueWatcher(去重入队)
→ nextTick 微任务 → flushSchedulerQueue → watcher.run → updateComponent
→ _render 新 VNode → __patch__(oldVnode, newVnode) → diff → 最小 DOM 操作
→ beforeUpdate / updated

Vue 3 对应

createApp().mount() → render(vnode, container) → patch(null, vnode) → processComponent → 组件 setup → renderComponentRoot → patch 子节点 → onMounted。首次挂载还会收集 mounted 钩子(异步队列 queuePostRenderEffect),在整棵树 patch 完成后统一执行——这点与 Vue 2 的「先子后父」一致。

面试可强调的点

  1. mounted 时子组件先于父组件触发(patch 递归先子后父,钩子进 post 队列);
  2. 首次 patch 是「全量创建」,没有 diff;diff 只在更新时发生;
  3. 挂载过程中 $el 会被替换(Vue 2 用 el 占位再替换),所以不要依赖原 el 引用。

本题来自 计算机知识面试题库,共 921 道题。