vue手动实现mvvm
Vue 手动实现 MVVM 的核心原理
MVVM(Model-View-ViewModel)的核心是数据绑定和响应式系统,Vue 通过数据劫持和发布-订阅模式实现。以下是关键实现步骤:
数据劫持(响应式系统)
使用 Object.defineProperty 或 Proxy 拦截数据的读写操作,在属性变化时触发更新。
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); // 收集当前 Watcher
return val;
},
set(newVal) {
if (newVal === val) return;
val = newVal;
dep.notify(); // 通知所有 Watcher 更新
}
});
}
}
依赖收集与发布订阅
通过 Dep(依赖管理器)和 Watcher(订阅者)实现视图更新。
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; // 标记当前 Watcher
this.oldValue = vm[key]; // 触发 getter 收集依赖
Dep.target = null;
}
update() {
const newValue = this.vm[this.key];
if (newValue !== this.oldValue) {
this.cb(newValue);
}
}
}
模板编译
将模板中的插值表达式和指令解析为数据绑定的逻辑。
class Compiler {
constructor(el, vm) {
this.vm = vm;
this.el = document.querySelector(el);
this.compile(this.el);
}
compile(node) {
Array.from(node.childNodes).forEach(child => {
if (this.isTextNode(child)) {
this.compileText(child);
} else if (this.isElementNode(child)) {
this.compileElement(child);
}
if (child.childNodes?.length) {
this.compile(child);
}
});
}
compileText(node) {
const reg = /\{\{(.*?)\}\}/g;
const text = node.textContent;
if (reg.test(text)) {
const key = RegExp.$1.trim();
node.textContent = text.replace(reg, this.vm[key]);
new Watcher(this.vm, key, val => {
node.textContent = text.replace(reg, val);
});
}
}
}
整合 MVVM 入口
将以上模块组合成完整的 MVVM 框架。
class MVVM {
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">{{ message }}</div>
<script>
const vm = new MVVM({
el: '#app',
data: { message: 'Hello MVVM' }
});
setTimeout(() => {
vm.message = 'Updated!'; // 视图自动更新
}, 1000);
</script>
关键点说明
- 数据劫持:通过
Object.defineProperty监听数据变化。 - 依赖收集:在
getter中收集依赖,在setter中触发更新。 - 模板编译:解析模板中的动态绑定,初始化视图并创建
Watcher。 - Proxy 替代方案:现代浏览器可使用
Proxy简化数据劫持逻辑(需处理兼容性)。







