自定义实现vue
自定义实现 Vue 的核心原理
Vue 的核心原理包括数据响应式、虚拟 DOM、模板编译等。以下分模块说明如何实现一个简化版 Vue。
数据响应式实现
通过 Object.defineProperty 或 Proxy 实现数据劫持,监听数据变化并触发更新。
class Observer {
constructor(data) {
this.walk(data)
}
walk(data) {
if (!data || typeof data !== 'object') return
Object.keys(data).forEach(key => {
this.defineReactive(data, key, data[key])
})
}
defineReactive(obj, key, val) {
const dep = new Dep()
this.walk(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
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 实现
创建虚拟节点并实现 diff 算法。
class VNode {
constructor(tag, data, children, text, elm) {
this.tag = tag
this.data = data
this.children = children
this.text = text
this.elm = elm
}
}
function createElement(tag, data, children) {
return new VNode(tag, data, children, undefined, undefined)
}
模板编译
将模板字符串编译为渲染函数。

function compile(template) {
const ast = parse(template)
const code = generate(ast)
return new Function(`with(this){return ${code}}`)
}
组件系统
实现组件注册和实例化。
class Vue {
constructor(options) {
this.$options = options
this._data = options.data
new Observer(this._data)
this._proxyData()
this.$mount(options.el)
}
_proxyData() {
Object.keys(this._data).forEach(key => {
Object.defineProperty(this, key, {
get() {
return this._data[key]
},
set(val) {
this._data[key] = val
}
})
})
}
$mount(el) {
this.$el = document.querySelector(el)
const updateComponent = () => {
this._update(this._render())
}
new Watcher(this, updateComponent)
}
_render() {
return this.$options.render.call(this)
}
_update(vnode) {
const prevVnode = this._vnode
this._vnode = vnode
if (!prevVnode) {
this.__patch__(this.$el, vnode)
} else {
this.__patch__(prevVnode, vnode)
}
}
}
Watcher 实现
连接响应式系统和视图更新。
class Watcher {
constructor(vm, expOrFn) {
this.vm = vm
this.getter = expOrFn
this.get()
}
get() {
Dep.target = this
this.getter.call(this.vm)
Dep.target = null
}
update() {
this.get()
}
}
以上代码实现了一个简化版 Vue 的核心功能,包括数据响应式、虚拟 DOM、模板编译和组件系统。实际 Vue 实现更复杂,包含更多优化和功能。






