实现简易vue
实现简易 Vue 的核心思路
简易 Vue 的实现主要围绕数据响应式、模板编译和依赖收集展开。以下是一个简化版 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
编译器实现
简单模板编译,将模板中的插值表达式替换为数据:

class Compiler {
constructor(el, vm) {
this.$vm = vm
this.$el = document.querySelector(el)
if (this.$el) {
this.compile(this.$el)
}
}
compile(el) {
const childNodes = el.childNodes
Array.from(childNodes).forEach(node => {
if (this.isElement(node)) {
this.compileElement(node)
} else if (this.isInterpolation(node)) {
this.compileText(node)
}
if (node.childNodes && node.childNodes.length > 0) {
this.compile(node)
}
})
}
isElement(node) {
return node.nodeType === 1
}
isInterpolation(node) {
return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent)
}
compileText(node) {
const exp = RegExp.$1.trim()
this.update(node, exp, 'text')
}
update(node, exp, dir) {
const updater = this[dir + 'Updater']
updater && updater(node, this.$vm[exp])
new Watcher(this.$vm, exp, value => {
updater && updater(node, value)
})
}
textUpdater(node, value) {
node.textContent = value
}
}
观察者实现
连接响应式数据和视图更新的桥梁:
class Watcher {
constructor(vm, key, cb) {
this.vm = vm
this.key = key
this.cb = cb
Dep.target = this
this.vm[this.key] // 触发getter,收集依赖
Dep.target = null
}
update() {
this.cb.call(this.vm, this.vm[this.key])
}
}
主框架整合
将各个模块组合成简易 Vue 类:
class Vue {
constructor(options) {
this.$options = options
this.$data = options.data
// 数据响应式
new Observer(this.$data)
// 代理data到Vue实例
Object.keys(this.$data).forEach(key => {
this._proxy(key)
})
// 编译模板
new Compiler(options.el, this)
}
_proxy(key) {
Object.defineProperty(this, key, {
get() {
return this.$data[key]
},
set(newVal) {
this.$data[key] = newVal
}
})
}
}
使用示例
<div id="app">
<p>{{ message }}</p>
</div>
<script>
const vm = new Vue({
el: '#app',
data: {
message: 'Hello Mini Vue!'
}
})
setTimeout(() => {
vm.message = 'Data changed!'
}, 1000)
</script>
这个简易实现包含了 Vue 最核心的响应式系统、模板编译和依赖收集机制。实际 Vue 的实现要复杂得多,包括虚拟 DOM、组件系统、指令系统等更多功能。






