实现简易vue
实现简易 Vue 的核心思路
Vue 的核心功能包括数据响应式、模板编译和虚拟 DOM。以下是一个简易实现方案,涵盖核心功能模块。
数据响应式系统
通过 Object.defineProperty 或 Proxy 实现数据劫持。以下使用 Object.defineProperty 的示例:

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]);
}
}
模板编译
实现简单的模板解析和指令处理:
class Compiler {
constructor(el, vm) {
this.$vm = vm;
this.$el = document.querySelector(el);
this.compile(this.$el);
}
compile(el) {
const childNodes = el.childNodes;
Array.from(childNodes).forEach(node => {
if (this.isElement(node)) {
this.compileElement(node);
} else if (this.isInterpolation(node)) {
this.compileText(node);
}
if (node.childNodes) this.compile(node);
});
}
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');
}
compileElement(node) {
const attrs = node.attributes;
Array.from(attrs).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');
}
update(node, exp, dir) {
const updater = dir + 'Updater';
this[updater](node, this.$vm[exp]);
new Watcher(this.$vm, exp, value => {
this[updater](node, value);
});
}
textUpdater(node, value) {
node.textContent = value;
}
}
整合成 MiniVue 类
将各模块组合成完整框架:
class MiniVue {
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>
<button v-text="count"></button>
</div>
<script>
const app = new MiniVue({
el: '#app',
data() {
return {
message: 'Hello MiniVue',
count: 0
};
}
});
setInterval(() => app.count++, 1000);
</script>
关键点说明
- 数据劫持:通过
Object.defineProperty监听属性变化 - 依赖收集:在 getter 中收集依赖,setter 中触发更新
- 模板编译:解析 DOM 节点,处理插值和指令
- 观察者模式:Watcher 作为桥梁连接数据变更和视图更新
此实现省略了虚拟 DOM、组件系统等复杂功能,但完整展示了 Vue 的响应式核心原理。






