简易实现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) {
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(node) {
const childNodes = node.childNodes
Array.from(childNodes).forEach(child => {
if (this.isElement(child)) {
this.compileElement(child)
} else if (this.isInterpolation(child)) {
this.compileText(child)
}
if (child.childNodes && child.childNodes.length > 0) {
this.compile(child)
}
})
}
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-')
}
compileText(node) {
const exp = RegExp.$1.trim()
this.update(node, exp, 'text')
}
text(node, exp) {
this.update(node, exp, 'text')
}
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
}
}
观察者
实现 Watcher 来连接视图和模型:
class Watcher {
constructor(vm, key, cb) {
this.vm = vm
this.key = key
this.cb = cb
Dep.target = this
this.oldValue = vm[key]
Dep.target = null
}
update() {
const newValue = this.vm[this.key]
if (newValue !== this.oldValue) {
this.cb(newValue)
this.oldValue = newValue
}
}
}
Vue 主类
整合以上功能实现 Vue 类:
class Vue {
constructor(options) {
this.$options = options
this.$data = options.data
new Observer(this.$data)
this.proxyData(this.$data)
new Compiler(options.el, this)
}
proxyData(data) {
Object.keys(data).forEach(key => {
Object.defineProperty(this, key, {
get() {
return data[key]
},
set(newVal) {
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 Vue',
btnText: 'Click me'
}
})
</script>
这个简易实现包含了 Vue 的核心功能:数据响应式、依赖收集和模板编译。实际 Vue 框架还包含虚拟 DOM、组件系统等更多复杂功能,但以上代码展示了 Vue 响应式原理的基本实现方式。







