手写vue双向绑定实现
实现 Vue 双向绑定的核心原理
Vue 的双向绑定基于 Object.defineProperty 或 Proxy(Vue 3)实现数据劫持,结合发布-订阅模式实现视图与数据的自动同步。以下是手写简化版实现:
数据劫持与响应式
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());
}
}
class Watcher {
constructor(vm, key, cb) {
this.vm = vm;
this.key = key;
this.cb = cb;
Dep.target = this;
this.oldValue = vm[key]; // 触发getter
Dep.target = null;
}
update() {
const newValue = this.vm[this.key];
if (newValue !== this.oldValue) {
this.cb(newValue);
this.oldValue = newValue;
}
}
}
编译器实现
class Compiler {
constructor(el, vm) {
this.vm = vm;
this.el = document.querySelector(el);
this.compile(this.el);
}
compile(node) {
node.childNodes.forEach(child => {
if (this.isElementNode(child)) {
this.compileElement(child);
} else if (this.isTextNode(child)) {
this.compileText(child);
}
if (child.childNodes.length) {
this.compile(child);
}
});
}
compileElement(node) {
Array.from(node.attributes).forEach(attr => {
if (this.isDirective(attr.name)) {
const dir = attr.name.substring(2);
this[dir] && this[dir](node, attr.value);
}
});
}
text(node, key) {
this.update(node, key, 'text');
}
model(node, key) {
this.update(node, key, 'model');
node.addEventListener('input', e => {
this.vm[key] = e.target.value;
});
}
update(node, key, dir) {
const updaterFn = this[`${dir}Updater`];
updaterFn && updaterFn(node, this.vm[key]);
new Watcher(this.vm, key, value => {
updaterFn(node, value);
});
}
textUpdater(node, value) {
node.textContent = value;
}
modelUpdater(node, value) {
node.value = value;
}
isDirective(attr) {
return attr.startsWith('v-');
}
isElementNode(node) {
return node.nodeType === 1;
}
isTextNode(node) {
return node.nodeType === 3;
}
}
整合实现
class Vue {
constructor(options) {
this.$options = options;
this.$data = options.data();
this.observe(this.$data);
new Compiler(options.el, this);
}
observe(data) {
new Observer(data);
}
}
使用示例
<div id="app">
<input v-model="message" />
<div v-text="message"></div>
</div>
<script>
new Vue({
el: '#app',
data() {
return { message: 'Hello Vue' };
}
});
</script>
关键点说明
- 数据劫持:通过
Object.defineProperty拦截数据的读写操作 - 依赖收集:在 getter 中收集依赖的 Watcher 实例
- 派发更新:在 setter 中通知所有 Watcher 执行更新
- 指令解析:编译模板时解析
v-model和v-text等指令 - 视图更新:通过 Watcher 实现数据变化时的自动视图更新
以上实现省略了数组处理、虚拟 DOM 等复杂逻辑,但完整展示了 Vue 双向绑定的核心机制。







