js 实现mvvm

MVVM 实现原理
MVVM(Model-View-ViewModel)是一种前端架构模式,核心在于数据绑定和视图与数据的自动同步。在 JavaScript 中实现 MVVM 通常需要以下几个关键部分:
- 数据劫持/代理:通过
Object.defineProperty或Proxy监听数据变化。 - 依赖收集:在数据读取时收集依赖(如模板中的变量),数据变化时通知依赖更新。
- 模板编译:解析模板中的指令(如
v-model、{{}}),绑定数据与视图。
核心代码实现
数据劫持(基于 Proxy)
class Observer {
constructor(data) {
return this.defineReactive(data);
}
defineReactive(data) {
const dep = new Dep();
return new Proxy(data, {
get(target, key) {
Dep.target && dep.addSub(Dep.target); // 收集依赖
return target[key];
},
set(target, key, value) {
target[key] = value;
dep.notify(); // 触发更新
return true;
},
});
}
}
依赖管理
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.el = document.querySelector(el);
this.vm = vm;
this.compile(this.el);
}
compile(node) {
Array.from(node.childNodes).forEach(child => {
if (child.nodeType === 3) { // 文本节点
this.compileText(child);
} else if (child.nodeType === 1) { // 元素节点
this.compileElement(child);
}
if (child.childNodes.length) {
this.compile(child);
}
});
}
compileText(node) {
const text = node.textContent;
const reg = /\{\{(.*?)\}\}/g;
if (reg.test(text)) {
const key = RegExp.$1.trim();
new Watcher(this.vm, key, val => {
node.textContent = text.replace(reg, val);
});
}
}
}
观察者(Watcher)
class Watcher {
constructor(vm, key, cb) {
this.vm = vm;
this.key = key;
this.cb = cb;
Dep.target = this;
this.vm[this.key]; // 触发 getter,收集依赖
Dep.target = null;
}
update() {
this.cb(this.vm[this.key]);
}
}
完整 MVVM 类
class MVVM {
constructor(options) {
this.$el = options.el;
this.$data = options.data;
new Observer(this.$data);
new Compiler(this.$el, this);
this.proxyData(this.$data);
}
proxyData(data) {
Object.keys(data).forEach(key => {
Object.defineProperty(this, key, {
get() {
return data[key];
},
set(newVal) {
data[key] = newVal;
},
});
});
}
}
使用示例
<div id="app">
<input v-model="message" />
<p>{{ message }}</p>
</div>
<script>
const vm = new MVVM({
el: '#app',
data: { message: 'Hello MVVM!' },
});
</script>
关键点说明
- 数据劫持:通过
Proxy或Object.defineProperty监听数据变化。 - 依赖收集:在模板编译过程中,解析
{{}}或指令时会创建Watcher,触发数据的getter从而收集依赖。 - 更新触发:数据变化时通过
setter通知Dep,进而调用所有Watcher的update方法更新视图。
此实现为简化版,实际框架(如 Vue)会处理更多边界条件和性能优化。







