vue手动实现mvvm
Vue 手动实现 MVVM 的核心思路
MVVM(Model-View-ViewModel)的核心是数据绑定和视图自动更新。以下是手动实现的关键步骤:
数据劫持(响应式数据)
通过 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();
}
});
});
}
依赖收集(Dep 类)
管理订阅者(Watcher)的依赖关系:

class Dep {
constructor() {
this.subs = [];
}
addSub(sub) {
this.subs.push(sub);
}
notify() {
this.subs.forEach(sub => sub.update());
}
}
Dep.target = null;
观察者(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.call(this.vm, this.vm[this.key]);
}
}
模板编译(Compiler)
解析 DOM 并绑定数据:
class Compiler {
constructor(el, vm) {
this.vm = vm;
this.el = document.querySelector(el);
this.compile(this.el);
}
compile(node) {
Array.from(node.childNodes).forEach(node => {
if (node.nodeType === 3) {
this.compileText(node);
} else if (node.nodeType === 1) {
this.compileElement(node);
}
if (node.childNodes.length) {
this.compile(node);
}
});
}
compileText(node) {
const reg = /\{\{(.*?)\}\}/g;
const text = node.textContent;
if (reg.test(text)) {
const key = RegExp.$1.trim();
node.textContent = this.vm[key];
new Watcher(this.vm, key, val => {
node.textContent = val;
});
}
}
compileElement(node) {
Array.from(node.attributes).forEach(attr => {
if (attr.name.startsWith('v-')) {
const dir = attr.name.substring(2);
const key = attr.value;
this[dir + 'Updater'](node, key);
}
});
}
modelUpdater(node, key) {
node.value = this.vm[key];
new Watcher(this.vm, key, val => {
node.value = val;
});
node.addEventListener('input', e => {
this.vm[key] = e.target.value;
});
}
}
整合实现 MVVM 类
class MVVM {
constructor(options) {
this.$options = options;
this.$data = options.data;
observe(this.$data);
Object.keys(this.$data).forEach(key => {
this.proxyData(key);
});
new Compiler(options.el, this);
}
proxyData(key) {
Object.defineProperty(this, key, {
get() {
return this.$data[key];
},
set(newVal) {
this.$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>
实现要点说明
- 数据劫持是响应式的核心,Vue 3 改用
Proxy实现更完善的监听 - 依赖收集确保只有依赖数据的视图部分会更新
- 模板编译将声明式模板转换为数据绑定的具体操作
- 通过代理将
data的属性直接暴露在 VM 实例上
以上实现省略了虚拟 DOM、组件系统等 Vue 的高级特性,但完整展示了 MVVM 的核心原理。






