vue原型实现
Vue 原型实现的关键点
Vue.js 的原型系统是其响应式机制的核心部分,通过原型链实现数据的动态绑定和依赖收集。以下是实现 Vue 原型的主要技术要点。
数据响应式原理
Vue 通过 Object.defineProperty 或 Proxy 实现数据的响应式。对象的每个属性会被转换为 getter/setter,用于依赖收集和派发更新。

function defineReactive(obj, key, val) {
Object.defineProperty(obj, key, {
get() {
console.log(`读取 ${key}`);
return val;
},
set(newVal) {
if (newVal !== val) {
console.log(`设置 ${key} 为 ${newVal}`);
val = newVal;
}
}
});
}
依赖收集与派发更新
Vue 通过 Dep 和 Watcher 实现依赖管理。Dep 是依赖的容器,Watcher 是观察者,负责执行更新操作。
class Dep {
constructor() {
this.subscribers = [];
}
depend() {
if (target && !this.subscribers.includes(target)) {
this.subscribers.push(target);
}
}
notify() {
this.subscribers.forEach(sub => sub());
}
}
let target = null;
function watcher(fn) {
target = fn;
fn();
target = null;
}
虚拟 DOM 与 Diff 算法
Vue 使用虚拟 DOM 提高渲染效率,通过 Diff 算法比较新旧虚拟 DOM 树的差异,最小化 DOM 操作。

function patch(oldVnode, vnode) {
if (oldVnode === vnode) return;
const el = oldVnode.el;
if (!vnode) {
el.parentNode.removeChild(el);
return;
}
if (typeof vnode === 'string') {
el.textContent = vnode;
return;
}
if (oldVnode.tag !== vnode.tag) {
const newEl = createEl(vnode);
el.parentNode.replaceChild(newEl, el);
return;
}
patchProps(el, oldVnode.props, vnode.props);
patchChildren(el, oldVnode.children, vnode.children);
}
组件系统实现
Vue 组件通过原型继承实现复用。每个组件实例共享相同的原型方法,但拥有独立的数据和作用域。
function VueComponent(options) {
this._init(options);
}
VueComponent.prototype._init = function(options) {
this.$options = options;
this._data = typeof options.data === 'function' ? options.data() : options.data;
this._el = options.el;
this._render();
};
生命周期钩子
Vue 的生命周期钩子通过调用特定阶段的回调函数实现。例如 created、mounted 等钩子会在对应时机触发。
VueComponent.prototype._callHook = function(hook) {
const handlers = this.$options[hook];
if (handlers) {
handlers.call(this);
}
};
以上内容展示了 Vue 原型实现的核心技术,包括响应式数据、依赖管理、虚拟 DOM 和组件系统。这些机制共同构成了 Vue.js 的底层架构。






