Vue核心实现源码
Vue 核心实现源码解析
Vue.js 的核心实现主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是关键部分的源码解析:
响应式系统
Vue 使用 Object.defineProperty(Vue 2)或 Proxy(Vue 3)实现数据劫持。核心代码在 src/core/observer 目录:
// Vue 2 的响应式实现
class Observer {
constructor(value) {
this.value = value
this.dep = new Dep()
def(value, '__ob__', this)
if (Array.isArray(value)) {
this.observeArray(value)
} else {
this.walk(value)
}
}
walk(obj) {
Object.keys(obj).forEach(key => {
defineReactive(obj, key)
})
}
}
虚拟 DOM 实现
虚拟 DOM 相关代码位于 src/core/vdom。VNode 类表示虚拟节点:

class VNode {
constructor(tag, data, children, text, elm) {
this.tag = tag
this.data = data
this.children = children
this.text = text
this.elm = elm
}
}
模板编译
模板编译流程在 src/compiler 目录,将模板转换为渲染函数:
function compileToFunctions(template) {
const ast = parse(template.trim())
optimize(ast)
const code = generate(ast)
return new Function(code.render)
}
组件系统
组件初始化代码在 src/core/instance/init.js:

export function initMixin(Vue) {
Vue.prototype._init = function(options) {
const vm = this
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
initLifecycle(vm)
initEvents(vm)
initRender(vm)
callHook(vm, 'beforeCreate')
initInjections(vm)
initState(vm)
initProvide(vm)
callHook(vm, 'created')
}
}
依赖收集
Dep 和 Watcher 实现响应式依赖关系:
class Dep {
constructor() {
this.subs = []
}
addSub(sub) {
this.subs.push(sub)
}
notify() {
this.subs.forEach(sub => sub.update())
}
}
class Watcher {
constructor(vm, expOrFn, cb) {
this.vm = vm
this.getter = parsePath(expOrFn)
this.cb = cb
this.value = this.get()
}
get() {
Dep.target = this
const value = this.getter.call(this.vm, this.vm)
Dep.target = null
return value
}
}
生命周期钩子
生命周期管理在 src/core/instance/lifecycle.js:
export function mountComponent(vm, el) {
vm.$el = el
callHook(vm, 'beforeMount')
const updateComponent = () => {
vm._update(vm._render())
}
new Watcher(vm, updateComponent, noop)
callHook(vm, 'mounted')
}
异步更新队列
异步更新实现位于 src/core/observer/scheduler.js:
const queue = []
let waiting = false
function flushSchedulerQueue() {
queue.sort((a, b) => a.id - b.id)
for (let i = 0; i < queue.length; i++) {
queue[i].run()
}
queue.length = 0
waiting = false
}
function queueWatcher(watcher) {
queue.push(watcher)
if (!waiting) {
waiting = true
nextTick(flushSchedulerQueue)
}
}
这些核心实现共同构成了 Vue 的响应式、组件化和渲染系统。源码结构清晰,各模块职责分明,通过观察者模式实现数据驱动视图的更新机制。





