简易实现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) {
this.walk(val) // 递归处理嵌套对象
const dep = new Dep()
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)
}
compileElement(node) {
const attrs = node.attributes
Array.from(attrs).forEach(attr => {
const attrName = attr.name
const exp = attr.value
if (this.isDirective(attrName)) {
const dir = attrName.substring(2)
this[dir] && this[dir](node, exp)
}
})
}
isDirective(attr) {
return attr.startsWith('v-')
}
text(node, exp) {
this.update(node, exp, 'text')
}
model(node, exp) {
this.update(node, exp, 'model')
node.addEventListener('input', e => {
this.$vm[exp] = e.target.value
})
}
update(node, exp, dir) {
const fn = this[dir + 'Updater']
fn && fn(node, this.$vm[exp])
new Watcher(this.$vm, exp, value => {
fn && fn(node, value)
})
}
textUpdater(node, value) {
node.textContent = value
}
modelUpdater(node, value) {
node.value = value
}
compileText(node) {
const exp = RegExp.$1.trim()
this.update(node, exp, 'text')
}
}
观察者实现
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)
Object.keys(this.$data).forEach(key => {
this.proxyData(key)
})
new Compiler(options.el, this)
}
proxyData(key) {
Object.defineProperty(this, key, {
get() {
return this.$data[key]
},
set(newVal) {
this.$data[key] = newVal
}
})
}
}
使用示例
<div id="app">
<p>{{ message }}</p>
<input v-model="message">
</div>
<script>
const vm = new Vue({
el: '#app',
data: {
message: 'Hello Mini Vue'
}
})
</script>
这个实现包含了 Vue 的核心功能:数据响应式、模板编译、指令处理。实际 Vue 源码更复杂,包含虚拟 DOM、组件系统等高级特性,但以上代码演示了最核心的响应式原理。







