从0实现vue
实现一个简易版Vue框架
要实现一个类似Vue的响应式框架,需要理解几个核心概念:数据响应式、虚拟DOM、模板编译和组件系统。以下是简化实现的关键步骤:
数据响应式系统
通过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)
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')
}
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')
}
html(node, exp) {
this.update(node, exp, 'html')
}
update(node, exp, dir) {
const updaterFn = this[dir + 'Updater']
updaterFn && updaterFn(node, this.$vm[exp])
new Watcher(this.$vm, exp, function(value) {
updaterFn && updaterFn(node, value)
})
}
textUpdater(node, value) {
node.textContent = value
}
htmlUpdater(node, value) {
node.innerHTML = 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)
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>
<button v-text="btnText"></button>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
message: 'Hello Mini Vue',
btnText: 'Click me'
}
})
</script>
这个实现包含了Vue最核心的响应式系统、模板编译和依赖收集功能。实际Vue还包含更多复杂功能如虚拟DOM diff算法、组件系统、生命周期钩子等,但以上代码已经展示了基本原理。







