用js实现vue
以下是用 JavaScript 实现 Vue 核心功能的简化方案,包括响应式数据绑定、模板编译和虚拟 DOM 更新:

响应式数据系统
通过 Object.defineProperty 或 Proxy 实现数据劫持:
class Observer {
constructor(data) {
this.observe(data)
}
observe(data) {
if (!data || typeof data !== 'object') return
Object.keys(data).forEach(key => {
this.defineReactive(data, key, data[key])
})
}
defineReactive(obj, key, value) {
const dep = new Dep()
this.observe(value)
Object.defineProperty(obj, key, {
get() {
Dep.target && dep.addSub(Dep.target)
return value
},
set: (newVal) => {
if (newVal === value) return
this.observe(newVal)
value = newVal
dep.notify()
}
})
}
}
class Dep {
constructor() {
this.subs = []
}
addSub(sub) {
this.subs.push(sub)
}
notify() {
this.subs.forEach(sub => sub.update())
}
}
虚拟 DOM 实现
class VNode {
constructor(tag, data, children, text, elm) {
this.tag = tag
this.data = data
this.children = children
this.text = text
this.elm = elm
}
}
function createElement(tag, data, children) {
return new VNode(tag, data, children, undefined, undefined)
}
function createTextNode(text) {
return new VNode(undefined, undefined, undefined, text, undefined)
}
模板编译
class Compiler {
constructor(el, vm) {
this.$vm = vm
this.$el = document.querySelector(el)
this.compile(this.$el)
}
compile(el) {
Array.from(el.childNodes).forEach(node => {
if (node.nodeType === 1) {
this.compileElement(node)
this.compile(node)
} else if (this.isInterpolation(node)) {
this.compileText(node)
}
})
}
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)
}
})
}
compileText(node) {
const exp = RegExp.$1.trim()
this.update(node, exp, 'text')
}
update(node, exp, dir) {
const updater = this[dir + 'Updater']
updater && updater(node, this.$vm[exp])
new Watcher(this.$vm, exp, value => {
updater && updater(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) return
this.cb(newValue)
this.oldValue = newValue
}
}
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 v-text="message"></p>
<input v-model="message">
</div>
<script>
const app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
</script>
这个实现包含了 Vue 的核心功能:
- 数据响应式系统
- 指令系统(v-text/v-model)
- 模板编译
- 依赖收集和派发更新
实际 Vue 源码更复杂,包含虚拟 DOM diff、组件系统、生命周期等更多功能,但以上代码展示了核心原理。







