实现简易vue
实现简易 Vue 的核心思路
实现一个简易 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; // 标记当前 Watcher
this.oldValue = vm[key]; // 触发 getter 收集依赖
Dep.target = null;
}
update() {
const newValue = this.vm[this.key];
if (newValue !== this.oldValue) {
this.cb(newValue);
}
}
}
模板编译
通过编译模板解析指令(如 v-model)和插值表达式(如 {{}}),并绑定更新函数。
class Compiler {
constructor(el, vm) {
this.$vm = vm;
this.$el = document.querySelector(el);
this.compile(this.$el);
}
compile(node) {
node.childNodes.forEach(child => {
if (child.nodeType === 1) { // 元素节点
this.compileElement(child);
} else if (child.nodeType === 3 && /\{\{(.*)\}\}/.test(child.textContent)) { // 文本节点
this.compileText(child, RegExp.$1);
}
if (child.childNodes.length) {
this.compile(child);
}
});
}
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);
}
});
}
compileText(node, key) {
this.update(node, key, 'text');
}
text(node, key) {
this.update(node, key, 'text');
}
model(node, key) {
this.update(node, key, 'model');
node.addEventListener('input', e => {
this.$vm[key] = e.target.value;
});
}
update(node, key, type) {
const updater = {
text: () => node.textContent = this.$vm[key],
model: () => node.value = this.$vm[key]
};
updater[type]();
new Watcher(this.$vm, key, () => updater[type]());
}
}
整合为 Vue 类
将上述模块整合为一个简易 Vue 类。
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>
<input v-model="message">
</div>
<script>
const app = new Vue({
el: '#app',
data() {
return { message: 'Hello Vue!' };
}
});
</script>
关键点说明
- 数据劫持:通过
Object.defineProperty监听属性变化。 - 依赖收集:在
getter中收集依赖,在setter中触发更新。 - 模板编译:解析 DOM 节点,绑定指令和插值表达式。
- 观察者模式:
Watcher作为中介,连接数据变更与视图更新。






