js 实现vue
在 JavaScript 中实现 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();
}
});
}
}
依赖收集系统
实现简单的发布-订阅模式来管理依赖:
class Dep {
constructor() {
this.subs = [];
}
addSub(sub) {
this.subs.push(sub);
}
notify() {
this.subs.forEach(sub => sub.update());
}
}
Dep.target = null;
编译模板
实现基础模板编译,将 {{}} 语法替换为数据:
class Compiler {
constructor(el, vm) {
this.$vm = vm;
this.$el = document.querySelector(el);
this.compile(this.$el);
}
compile(node) {
const childNodes = node.childNodes;
Array.from(childNodes).forEach(child => {
if (this.isElement(child)) {
this.compileElement(child);
} else if (this.isInterpolation(child)) {
this.compileText(child);
}
if (child.childNodes) {
this.compile(child);
}
});
}
isElement(node) {
return node.nodeType === 1;
}
isInterpolation(node) {
return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent);
}
compileText(node) {
const exp = RegExp.$1.trim();
this.update(node, exp, 'text');
}
update(node, exp, dir) {
const updater = dir + 'Updater';
this[updater] && this[updater](node, this.$vm[exp]);
new Watcher(this.$vm, exp, value => {
this[updater] && this[updater](node, value);
});
}
textUpdater(node, value) {
node.textContent = value;
}
}
观察者实现
创建观察者来连接响应式数据和视图更新:
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]);
}
}
主类实现
整合以上功能创建主类:
class Vue {
constructor(options) {
this.$options = options;
this.$data = options.data();
new Observer(this.$data);
this.proxyData(this.$data);
new Compiler(options.el, this);
}
proxyData(data) {
Object.keys(data).forEach(key => {
Object.defineProperty(this, key, {
get() {
return data[key];
},
set(newVal) {
data[key] = newVal;
}
});
});
}
}
使用示例
<div id="app">
<p>{{ message }}</p>
</div>
<script>
const app = new Vue({
el: '#app',
data() {
return {
message: 'Hello Vue!'
};
}
});
setTimeout(() => {
app.message = 'Updated!';
}, 1000);
</script>
注意事项
- 以上实现仅为简化版,Vue 实际源码更复杂,包含虚拟 DOM、组件系统等
- 现代 Vue 3 使用
Proxy代替Object.defineProperty实现响应式 - 完整实现需处理数组变化、指令系统、生命周期等更多功能
- 建议参考 Vue 源码学习完整实现细节







