实现简单vue
实现一个简单的 Vue 框架
数据响应式系统
通过 Object.defineProperty 实现数据劫持,监听数据变化:
function defineReactive(obj, key, val) {
const dep = new Dep()
Object.defineProperty(obj, key, {
get() {
Dep.target && dep.addSub(Dep.target)
return val
},
set(newVal) {
if (newVal === val) return
val = newVal
dep.notify()
}
})
}
依赖收集系统
实现一个简单的发布-订阅模式:
class Dep {
constructor() {
this.subs = []
}
addSub(sub) {
this.subs.push(sub)
}
notify() {
this.subs.forEach(sub => sub.update())
}
}
Dep.target = null
虚拟 DOM 实现
使用 JavaScript 对象表示 DOM 结构:
function createElement(tag, props, children) {
return {
tag,
props,
children
}
}
编译模板
将模板字符串转换为渲染函数:

function compile(template) {
const ast = parse(template)
const code = generate(ast)
return new Function(`with(this){return ${code}}`)
}
组件系统
实现基础的组件机制:
class Component {
constructor(options) {
this.$options = options
this._data = options.data()
this._proxyData()
this.$el = null
}
_proxyData() {
for (let key in this._data) {
defineReactive(this, key, this._data[key])
}
}
$mount(el) {
this.$el = document.querySelector(el)
const updateComponent = () => {
const vnode = this.$options.render.call(this)
patch(this.$el, vnode)
}
new Watcher(this, updateComponent)
}
}
观察者模式
实现数据变化时的自动更新:
class Watcher {
constructor(vm, fn) {
this.vm = vm
this.getter = fn
this.get()
}
get() {
Dep.target = this
this.getter()
Dep.target = null
}
update() {
this.get()
}
}
使用方法
创建 Vue 实例并挂载:

const app = new Component({
data() {
return {
message: 'Hello Vue'
}
},
render() {
return createElement('div', null, this.message)
}
})
app.$mount('#app')
核心功能实现要点
响应式原理
通过递归遍历 data 对象的属性,将其转换为 getter/setter 形式。当数据被访问时收集依赖,数据变化时通知所有依赖进行更新。
虚拟 DOM 差异算法
实现简单的 diff 算法比较新旧虚拟 DOM 树的差异,仅更新发生变化的部分:
function patch(oldVnode, vnode) {
if (oldVnode.nodeType) {
const parent = oldVnode.parentNode
const el = createElm(vnode)
parent.insertBefore(el, oldVnode.nextSibling)
parent.removeChild(oldVnode)
return el
}
}
生命周期钩子
可以扩展基础组件类添加生命周期方法:
class Component {
// ...
$mount(el) {
this.callHook('beforeMount')
// ...挂载逻辑
this.callHook('mounted')
}
callHook(hook) {
const handlers = this.$options[hook]
handlers && handlers.call(this)
}
}
这个简单实现包含了 Vue 的核心功能:响应式数据绑定、虚拟 DOM、组件系统和模板编译。实际 Vue 的实现更为复杂,包括更多优化和功能特性。






