简单实现vue
实现一个简易 Vue 框架
以下是一个基于 JavaScript 的简易 Vue 实现,核心功能包括数据响应式、模板编译和依赖收集。
数据响应式
通过 Object.defineProperty 实现数据劫持:
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) {
this.update(node, this.$vm, RegExp.$1, '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, this.$vm, exp)
}
})
}
isDirective(attr) {
return attr.indexOf('v-') === 0
}
text(node, vm, exp) {
this.update(node, vm, exp, 'text')
}
update(node, vm, exp, dir) {
const updaterFn = updater[dir + 'Updater']
updaterFn && updaterFn(node, vm[exp])
new Watcher(vm, exp, function(value) {
updaterFn && updaterFn(node, value)
})
}
}
const updater = {
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) return
this.cb(newValue)
}
}
主类
整合所有功能的 Vue 类:
class Vue {
constructor(options) {
this.$options = options
this.$data = options.data
new Observer(this.$data)
this.proxy(this.$data)
new Compiler(options.el, this)
}
proxy(data) {
Object.keys(data).forEach(key => {
Object.defineProperty(this, key, {
get() {
return data[key]
},
set(newVal) {
data[key] = newVal
}
})
})
}
}
使用示例
<div id="app">
{{message}}
<div v-text="message"></div>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
</script>
这个实现包含了 Vue 的核心功能:
- 数据响应式
- 模板编译
- 指令解析
- 依赖收集和更新
可以根据需要进一步扩展功能,如添加计算属性、事件处理等。






