自己实现vue
实现简易版 Vue.js 核心功能
要实现一个简易版 Vue.js,需要理解其核心功能:数据响应式、模板编译、依赖收集和虚拟 DOM。以下分模块实现关键功能。
数据响应式(Reactivity)
通过 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) {
this.walk(val); // 递归处理嵌套对象
const dep = new Dep();
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(); // 通知更新
}
});
}
}
依赖收集(Dependency Tracking)
通过发布-订阅模式管理依赖关系,每个响应式属性对应一个 Dep 实例。
class Dep {
constructor() {
this.subs = [];
}
addSub(sub) {
this.subs.push(sub);
}
notify() {
this.subs.forEach(sub => sub.update());
}
}
Dep.target = null; // 静态属性指向当前 Watcher
观察者(Watcher)
Watcher 作为中介,在数据变化时触发回调(如更新视图)。

class Watcher {
constructor(vm, key, cb) {
this.vm = vm;
this.key = key;
this.cb = cb;
Dep.target = this;
this.oldValue = vm[key]; // 触发 getter 收集依赖
Dep.target = null;
}
update() {
const newValue = this.vm[this.key];
if (newValue === this.oldValue) return;
this.cb(newValue);
this.oldValue = newValue;
}
}
模板编译(Compilation)
解析模板中的指令(如 v-model)和插值表达式({{}}),绑定数据和事件。
class Compiler {
constructor(el, vm) {
this.$vm = vm;
this.$el = document.querySelector(el);
this.compile(this.$el);
}
compile(node) {
node.childNodes.forEach(node => {
if (node.nodeType === 1) this.compileElement(node);
else if (this.isInterpolation(node)) this.compileText(node);
if (node.childNodes.length > 0) this.compile(node);
});
}
isInterpolation(node) {
return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent);
}
compileText(node) {
const exp = RegExp.$1.trim();
this.update(node, exp, 'text');
}
compileElement(node) {
Array.from(node.attributes).forEach(attr => {
if (attr.name.startsWith('v-')) {
const dir = attr.name.substring(2);
this[dir] && this[dir](node, attr.value);
}
});
}
text(node, exp) {
this.update(node, exp, 'text');
}
model(node, exp) {
this.update(node, exp, 'model');
node.addEventListener('input', e => {
this.$vm[exp] = e.target.value;
});
}
update(node, exp, dir) {
const updater = dir + 'Updater';
this[updater] && this[updater](node, this.$vm[exp]);
new Watcher(this.$vm, exp, value => {
this[updater](node, value);
});
}
textUpdater(node, value) {
node.textContent = value;
}
modelUpdater(node, value) {
node.value = value;
}
}
整合为 Vue 类
将上述模块组合成完整的 Vue 类。
class Vue {
constructor(options) {
this.$options = options;
this.$data = options.data();
this.observe(this.$data);
this.proxyData(this.$data);
new Compiler(options.el, this);
}
observe(data) {
new Observer(data);
}
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>
<input v-model="message">
</div>
<script>
const app = new Vue({
el: '#app',
data() {
return { message: 'Hello Mini Vue!' };
}
});
</script>
关键点总结
- 数据响应式:通过劫持数据属性的访问和修改,实现自动更新。
- 依赖收集:在
getter中收集依赖,在setter中触发更新。 - 模板编译:解析指令和插值,建立数据与 DOM 的绑定关系。
- 观察者模式:
Watcher作为桥梁连接数据变更与视图更新。
以上实现省略了虚拟 DOM、组件系统等高级功能,但涵盖了 Vue 最核心的响应式原理。






