实现简易vue
实现简易 Vue 的核心思路
Vue 的核心是数据响应式系统和虚拟 DOM 机制。简易实现需要关注以下几个关键部分:
数据响应式系统
通过 Object.defineProperty 或 Proxy 实现数据劫持,在数据变化时触发更新:
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()
}
})
}
依赖收集与发布订阅
实现一个简单的 Dep 和 Watcher 类来处理依赖:
class Dep {
constructor() {
this.subs = []
}
addSub(sub) {
this.subs.push(sub)
}
notify() {
this.subs.forEach(sub => sub.update())
}
}
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])
}
}
模板编译
实现一个简单的编译器来处理模板中的插值和指令:
class Compiler {
constructor(el, vm) {
this.$vm = vm
this.$el = document.querySelector(el)
this.compile(this.$el)
}
compile(node) {
Array.from(node.childNodes).forEach(node => {
if (node.nodeType === 1) {
this.compileElement(node)
} else if (this.isInterpolation(node)) {
this.compileText(node)
}
if (node.childNodes.length > 0) {
this.compile(node)
}
})
}
isInterpolation(node) {
return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent)
}
compileText(node) {
const key = RegExp.$1.trim()
node.textContent = this.$vm[key]
new Watcher(this.$vm, key, value => {
node.textContent = value
})
}
compileElement(node) {
Array.from(node.attributes).forEach(attr => {
if (attr.name.startsWith('v-')) {
const dir = attr.name.substring(2)
this[dir] && this[dir](node, attr.value)
}
})
}
}
整合实现
将这些部分组合成一个简易 Vue 类:
class Vue {
constructor(options) {
this.$options = options
this.$data = options.data
this.observe(this.$data)
new Compiler(options.el, this)
}
observe(obj) {
Object.keys(obj).forEach(key => {
defineReactive(obj, key, obj[key])
Object.defineProperty(this, key, {
get() {
return this.$data[key]
},
set(newVal) {
this.$data[key] = newVal
}
})
})
}
}
使用方法
这样实现的简易 Vue 可以这样使用:
<div id="app">
{{ message }}
</div>
<script>
const app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
</script>
功能扩展方向
这个简易实现可以进一步扩展:

- 添加 v-model 指令实现双向绑定
- 实现 computed 计算属性
- 添加 methods 方法支持
- 实现组件系统
- 使用虚拟 DOM 优化更新性能
以上实现展示了 Vue 最核心的响应式原理和模板编译机制,实际 Vue 的实现更加复杂和完善,但基本原理是相通的。






