手动实现合计vue
手动实现 Vue 的响应式系统
Vue 的核心之一是响应式系统,通过 Object.defineProperty 或 Proxy 实现数据绑定。以下是一个简化版的实现:

// 简易响应式实现
function defineReactive(obj, key, val) {
const dep = new Dep();
Object.defineProperty(obj, key, {
get() {
dep.depend(); // 收集依赖
return val;
},
set(newVal) {
if (newVal === val) return;
val = newVal;
dep.notify(); // 触发更新
}
});
}
// 依赖收集器
class Dep {
constructor() {
this.subscribers = [];
}
depend() {
if (target && !this.subscribers.includes(target)) {
this.subscribers.push(target);
}
}
notify() {
this.subscribers.forEach(sub => sub());
}
}
虚拟 DOM 实现
Vue 使用虚拟 DOM 提高渲染效率。以下是基础实现:

// 创建虚拟节点
function createElement(tag, props, children) {
return { tag, props, children };
}
// 渲染虚拟 DOM 到真实 DOM
function render(vnode) {
if (typeof vnode === 'string') return document.createTextNode(vnode);
const el = document.createElement(vnode.tag);
for (const key in vnode.props) {
el.setAttribute(key, vnode.props[key]);
}
vnode.children.forEach(child => el.appendChild(render(child)));
return el;
}
组件系统实现
Vue 组件是核心功能之一,以下是简化版实现:
class Component {
constructor(options) {
this.$options = options;
this._data = options.data();
this._el = null;
this._proxyData();
this.$mount();
}
_proxyData() {
Object.keys(this._data).forEach(key => {
defineReactive(this, key, this._data[key]);
});
}
$mount() {
this._el = render(this.$options.render.call(this));
document.querySelector(this.$options.el).appendChild(this._el);
}
}
使用示例
const app = new Component({
el: '#app',
data() {
return { message: 'Hello Vue' };
},
render() {
return createElement('div', {}, [
createElement('h1', {}, [this.message]),
createElement('button', { onClick: () => this.message = 'Updated' }, ['Click'])
]);
}
});
双向绑定实现
通过 v-model 指令实现双向绑定:
function compile(el, vm) {
el.querySelectorAll('[v-model]').forEach(node => {
const prop = node.getAttribute('v-model');
node.value = vm[prop];
node.addEventListener('input', e => {
vm[prop] = e.target.value;
});
});
}
以上代码展示了 Vue 核心功能的简化实现,实际 Vue 源码更复杂,包含优化和更多功能。






