vue 原理简易实现
Vue 原理简易实现
Vue 的核心原理包括响应式数据绑定、虚拟 DOM 和模板编译。以下是一个简化版的实现,展示 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);
return val;
},
set(newVal) {
if (newVal === val) return;
val = newVal;
dep.notify(); // 数据变化时通知依赖更新
}
});
}
}
依赖收集与派发更新
通过 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;
this.vm[this.key]; // 触发 getter,收集依赖
Dep.target = null;
}
update() {
this.cb.call(this.vm, this.vm[this.key]);
}
}
虚拟 DOM 与 Diff 算法
简化版的虚拟 DOM 实现,通过比较新旧虚拟 DOM 树来最小化 DOM 操作。
class VNode {
constructor(tag, data, children, text) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
}
}
function patch(oldVnode, vnode) {
if (!oldVnode) {
// 首次渲染
createElm(vnode);
} else {
// 更新逻辑
const isRealElement = oldVnode.nodeType;
if (isRealElement) {
// 初次渲染替换真实 DOM
const parent = oldVnode.parentNode;
const elm = createElm(vnode);
parent.insertBefore(elm, oldVnode);
parent.removeChild(oldVnode);
} else {
// Diff 算法简化版
if (oldVnode.tag !== vnode.tag) {
// 标签不同直接替换
oldVnode.el.parentNode.replaceChild(createElm(vnode), oldVnode.el);
} else {
// 更新属性
const el = (vnode.el = oldVnode.el);
updateProps(el, vnode.data, oldVnode.data);
// 更新子节点
patchChildren(el, oldVnode.children, vnode.children);
}
}
}
}
模板编译
将模板字符串转换为渲染函数。
function compile(template) {
const ast = parse(template); // 解析模板为 AST
const code = generate(ast); // 生成渲染函数代码
return new Function(`with(this){return ${code}}`);
}
// 示例 AST 转换(简化版)
function parse(template) {
const stack = [];
let root;
let currentParent;
parseHTML(template, {
start(tag, attrs) {
const element = { tag, attrs, children: [] };
if (!root) root = element;
if (currentParent) currentParent.children.push(element);
stack.push(element);
currentParent = element;
},
end() {
stack.pop();
currentParent = stack[stack.length - 1];
},
chars(text) {
currentParent.children.push({ text });
}
});
return root;
}
整合实现
将以上部分整合为一个简易的 Vue 类。
class Vue {
constructor(options) {
this.$options = options;
this._data = options.data();
new Observer(this._data);
this._proxyData();
this.$mount(options.el);
}
_proxyData() {
Object.keys(this._data).forEach(key => {
Object.defineProperty(this, key, {
get() {
return this._data[key];
},
set(newVal) {
this._data[key] = newVal;
}
});
});
}
$mount(el) {
this.$el = document.querySelector(el);
const updateComponent = () => {
const vnode = this.$options.render.call(this);
patch(this._vnode || this.$el, vnode);
this._vnode = vnode;
};
new Watcher(this, updateComponent);
}
}
使用示例
const app = new Vue({
el: '#app',
data() {
return { message: 'Hello Vue!' };
},
render() {
return h('div', null, this.message);
}
});
以上代码展示了 Vue 的核心原理简化实现,包括响应式系统、虚拟 DOM 和模板编译。实际 Vue 源码更加复杂,但基本原理与此类似。







