vue mvvm 实现
Vue MVVM 实现原理
Vue 的 MVVM(Model-View-ViewModel)实现主要依赖于数据绑定和响应式系统。以下是其核心实现机制:
数据劫持与响应式
Vue 通过 Object.defineProperty(Vue 2)或 Proxy(Vue 3)劫持数据对象的属性访问和修改。当数据变化时,触发依赖的视图更新。
// Vue 2 数据劫持示例
function defineReactive(obj, key, val) {
Object.defineProperty(obj, key, {
get() {
console.log('get', key);
return val;
},
set(newVal) {
if (newVal !== val) {
console.log('set', key);
val = newVal;
}
}
});
}
依赖收集与发布订阅
每个响应式属性关联一个 Dep(依赖收集器),在 getter 中收集依赖(Watcher),在 setter 中通知更新。
class Dep {
constructor() {
this.subs = [];
}
addSub(sub) {
this.subs.push(sub);
}
notify() {
this.subs.forEach(sub => sub.update());
}
}
虚拟 DOM 与 Diff 算法
Vue 将模板编译为虚拟 DOM(VNode),通过 Diff 算法比对变化后生成最小化 DOM 操作。
function patch(oldVnode, vnode) {
if (sameVnode(oldVnode, vnode)) {
patchVnode(oldVnode, vnode);
} else {
const parent = oldVnode.parentNode;
parent.insertBefore(createElm(vnode), oldVnode);
parent.removeChild(oldVnode);
}
}
模板编译
Vue 将模板编译为渲染函数,通过 with 语句和 new Function 生成可执行代码。
function compile(template) {
const ast = parse(template);
const code = generate(ast);
return new Function(`with(this){return ${code}}`);
}
实现简易 MVVM
以下是简化版实现流程:
-
数据监听
function observe(data) { if (typeof data !== 'object') return; Object.keys(data).forEach(key => { defineReactive(data, key, data[key]); }); } -
编译模板
function compile(el, vm) { el.childNodes.forEach(node => { if (node.nodeType === 1) { compileElement(node, vm); } else if (node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent)) { compileText(node, vm); } }); } -
Watcher 实现

class Watcher { constructor(vm, key, updateFn) { this.vm = vm; this.key = key; this.updateFn = updateFn; Dep.target = this; this.vm[this.key]; // 触发getter收集依赖 Dep.target = null; } update() { this.updateFn.call(this.vm, this.vm[this.key]); } }
关键设计模式
- 观察者模式:通过 Dep 和 Watcher 实现数据与视图的联动
- 代理模式:Vue 3 的 Proxy 拦截对象操作
- 装饰器模式:通过
@Component等装饰器增强类功能
Vue 的 MVVM 实现通过数据驱动视图,开发者只需关注数据状态,DOM 操作由框架自动完成。这种设计显著提高了开发效率和代码可维护性。






