js实现mvvm
MVVM 模式简介
MVVM(Model-View-ViewModel)是一种前端架构模式,通过数据绑定实现视图(View)与数据模型(Model)的分离。ViewModel 作为中间层,负责处理业务逻辑和数据转换,View 自动响应数据变化。
核心实现步骤
数据劫持(响应式数据)
使用 Object.defineProperty 或 Proxy 监听数据变化,触发更新逻辑。
// Proxy 实现
const data = { text: 'Hello' };
const reactiveData = new Proxy(data, {
set(target, key, value) {
target[key] = value;
updateView(); // 触发视图更新
return true;
}
});
模板编译
解析 HTML 模板中的指令(如 v-model、{{}}),将动态数据与 DOM 绑定。
function compile(template) {
const el = document.querySelector(template);
const nodes = el.childNodes;
nodes.forEach(node => {
if (node.nodeType === 3) { // 文本节点
const text = node.textContent;
const reg = /\{\{(.*?)\}\}/g;
if (reg.test(text)) {
const key = RegExp.$1.trim();
node.textContent = data[key]; // 初始化数据
// 监听变化,更新视图
watch(key, (newVal) => {
node.textContent = newVal;
});
}
}
});
}
依赖收集与观察者
通过 Dep(依赖管理器)和 Watcher(观察者)实现数据变更时的精准更新。
class Dep {
constructor() {
this.subs = [];
}
addSub(watcher) {
this.subs.push(watcher);
}
notify() {
this.subs.forEach(watcher => watcher.update());
}
}
class Watcher {
constructor(key, updateFn) {
this.key = key;
this.updateFn = updateFn;
Dep.target = this; // 全局暂存 Watcher
this.updateFn(); // 触发 getter 收集依赖
Dep.target = null;
}
update() {
this.updateFn();
}
}
双向绑定(v-model)
将表单输入与数据模型同步,通常通过事件监听实现。
function bindInput(modelKey) {
const input = document.querySelector(`[v-model="${modelKey}"]`);
input.addEventListener('input', (e) => {
reactiveData[modelKey] = e.target.value; // 触发 Proxy.set
});
}
完整示例
整合上述模块,实现一个简易 MVVM:

class MiniMVVM {
constructor(options) {
this.$el = document.querySelector(options.el);
this.$data = options.data;
this.proxyData();
this.compile(this.$el);
}
proxyData() {
for (let key in this.$data) {
Object.defineProperty(this, key, {
get() {
return this.$data[key];
},
set(newVal) {
this.$data[key] = newVal;
updateView(); // 实际应触发 Watcher 更新
}
});
}
}
compile(node) {
// 实现模板解析与指令绑定
}
}
注意事项
- 现代框架(如 Vue 3)使用
Proxy替代Object.defineProperty,支持深层对象监听。 - 性能优化需避免频繁 DOM 操作,可通过虚拟 DOM 或批处理更新实现。
- 实际项目中建议直接使用 Vue 或 React 等成熟框架。






