手动实现合计vue
手动实现简易 Vue 数据绑定
实现一个类似 Vue 的数据绑定系统,核心是数据劫持(响应式)和依赖收集(观察者模式)。以下是一个简化版实现:
1. 数据劫持(响应式)
通过 Object.defineProperty 或 Proxy 拦截数据变化:

function observe(data) {
if (!data || typeof data !== 'object') return;
Object.keys(data).forEach(key => {
let value = data[key];
const dep = new Dep(); // 每个属性对应一个依赖管理器
observe(value); // 递归处理嵌套对象
Object.defineProperty(data, key, {
get() {
Dep.target && dep.addSub(Dep.target); // 收集依赖
return value;
},
set(newVal) {
if (newVal === value) return;
value = newVal;
observe(newVal); // 新值是对象时继续劫持
dep.notify(); // 通知所有订阅者
}
});
});
}
2. 依赖管理器(Dep) 管理所有依赖(Watcher):
class Dep {
constructor() {
this.subs = [];
}
addSub(sub) {
this.subs.push(sub);
}
notify() {
this.subs.forEach(sub => sub.update());
}
}
Dep.target = null; // 静态属性指向当前Watcher
3. 观察者(Watcher) 连接数据变更与视图更新:

class Watcher {
constructor(vm, exp, cb) {
this.vm = vm;
this.exp = exp;
this.cb = cb;
this.value = this.get();
}
get() {
Dep.target = this;
const value = this.vm._data[this.exp]; // 触发getter收集依赖
Dep.target = null;
return value;
}
update() {
const newVal = this.vm._data[this.exp];
if (newVal !== this.value) {
this.value = newVal;
this.cb(newVal);
}
}
}
4. 编译器(Compile) 解析模板指令:
function compile(el, vm) {
vm.$el = document.querySelector(el);
const fragment = document.createDocumentFragment();
let child;
while (child = vm.$el.firstChild) {
fragment.appendChild(child);
}
replace(fragment, vm);
vm.$el.appendChild(fragment);
}
function replace(node, vm) {
const reg = /\{\{(.*?)\}\}/g;
if (node.nodeType === 3) {
const text = node.textContent;
if (reg.test(text)) {
const exp = RegExp.$1.trim();
node.textContent = text.replace(reg, vm._data[exp]);
new Watcher(vm, exp, val => {
node.textContent = text.replace(reg, val);
});
}
return;
}
if (node.nodeType === 1 && node.tagName === 'INPUT') {
const attrs = Array.from(node.attributes);
attrs.forEach(attr => {
if (attr.name === 'v-model') {
const exp = attr.value;
node.value = vm._data[exp];
new Watcher(vm, exp, val => {
node.value = val;
});
node.addEventListener('input', e => {
vm._data[exp] = e.target.value;
});
}
});
}
Array.from(node.childNodes).forEach(child => replace(child, vm));
}
5. 主类实现
class MyVue {
constructor(options) {
this._data = options.data;
observe(this._data);
compile(options.el, this);
}
}
使用示例
<div id="app">
<input v-model="message">
<p>{{ message }}</p>
</div>
<script>
new MyVue({
el: '#app',
data: {
message: 'Hello Mini Vue!'
}
});
</script>
关键点说明
- 数据劫持:通过
Object.defineProperty拦截属性的读取和修改 - 依赖收集:在 getter 中收集依赖(Watcher),在 setter 中触发更新
- 观察者模式:Watcher 作为观察者,Dep 作为被观察者
- 模板编译:通过正则匹配模板中的
{{}}和指令(如v-model)
这个实现省略了 Vue 的虚拟 DOM、组件系统等复杂功能,但包含了响应式系统的核心原理。现代 Vue 3 改用 Proxy 实现响应式,但核心思想仍保持一致。






