vue vm实现原理
Vue VM 实现原理
Vue 的 ViewModel(VM)实现原理主要基于数据劫持和依赖收集,通过响应式系统实现数据和视图的自动同步。
数据劫持
Vue 使用 Object.defineProperty(Vue 2.x)或 Proxy(Vue 3.x)对数据进行劫持。当数据被访问或修改时,能够触发相应的 getter 和 setter 函数。
// Vue 2.x 数据劫持示例
const data = { name: 'Vue' };
Object.defineProperty(data, 'name', {
get() {
console.log('获取 name');
return this._name;
},
set(newVal) {
console.log('设置 name');
this._name = newVal;
}
});
依赖收集
Vue 通过依赖收集跟踪数据的依赖关系。每个响应式数据属性都有一个对应的 Dep 实例,用于存储依赖该数据的 Watcher 实例。

class Dep {
constructor() {
this.subscribers = [];
}
depend() {
if (target && !this.subscribers.includes(target)) {
this.subscribers.push(target);
}
}
notify() {
this.subscribers.forEach(sub => sub());
}
}
观察者模式
Vue 使用 Watcher 实例作为观察者,负责在数据变化时更新视图。每个组件实例对应一个 Watcher,当数据变化时,Watcher 会触发重新渲染。
class Watcher {
constructor(vm, expOrFn, cb) {
this.vm = vm;
this.getter = parsePath(expOrFn);
this.cb = cb;
this.value = this.get();
}
get() {
target = this;
const value = this.getter.call(this.vm, this.vm);
target = undefined;
return value;
}
update() {
const oldValue = this.value;
this.value = this.get();
this.cb.call(this.vm, this.value, oldValue);
}
}
虚拟 DOM
Vue 使用虚拟 DOM 提高渲染效率。当数据变化时,Vue 会生成新的虚拟 DOM 树,并通过 diff 算法比较新旧虚拟 DOM,最终只更新必要的真实 DOM。

function patch(oldVnode, vnode) {
if (sameVnode(oldVnode, vnode)) {
patchVnode(oldVnode, vnode);
} else {
const parent = oldVnode.parentNode;
const elm = createElm(vnode);
parent.insertBefore(elm, oldVnode);
parent.removeChild(oldVnode);
}
return vnode.elm;
}
模板编译
Vue 将模板编译为渲染函数。模板中的指令和插值表达式会被转换为 JavaScript 代码,生成虚拟 DOM。
// 模板
<div>{{ message }}</div>
// 编译后的渲染函数
function render() {
with(this) {
return _c('div', [_v(_s(message))]);
}
}
组件系统
Vue 的组件系统基于原型继承。每个组件实例继承自 Vue 原型,拥有独立的响应式数据、计算属性、方法等。
const Sub = function VueComponent(options) {
this._init(options);
};
Sub.prototype = Object.create(Vue.prototype);
Sub.prototype.constructor = Sub;
生命周期钩子
Vue 在组件创建和更新的不同阶段调用生命周期钩子函数。这些钩子允许开发者在特定时机执行自定义逻辑。
function callHook(vm, hook) {
const handlers = vm.$options[hook];
if (handlers) {
handlers.call(vm);
}
}
总结
Vue 的 VM 实现通过数据劫持、依赖收集、观察者模式、虚拟 DOM 等技术,实现了数据和视图的自动同步。这种响应式系统是 Vue 高效更新的核心机制。






