从0实现vue
实现简易 Vue 的核心模块
数据响应式系统
通过 Object.defineProperty 或 Proxy 监听数据变化。以下为基于 Object.defineProperty 的简化实现:
function defineReactive(obj, key, val) {
const dep = new Dep();
Object.defineProperty(obj, key, {
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) {
Dep.target = this;
this.vm = vm;
this.key = key;
this.cb = cb;
this.value = vm[key]; // 触发getter
Dep.target = null;
}
update() {
this.value = this.vm[this.key];
this.cb(this.value);
}
}
模板编译
解析 DOM 模板
将模板中的 {{}} 和指令转换为数据绑定:

function compile(el, vm) {
const fragment = document.createDocumentFragment();
let child;
while (child = el.firstChild) {
fragment.appendChild(child);
}
function replace(frag) {
Array.from(frag.childNodes).forEach(node => {
const txt = node.textContent;
const reg = /\{\{(.*?)\}\}/g;
if (node.nodeType === 3 && reg.test(txt)) {
const key = RegExp.$1.trim();
new Watcher(vm, key, newVal => {
node.textContent = txt.replace(reg, newVal);
});
node.textContent = txt.replace(reg, vm[key]);
}
if (node.childNodes) replace(node);
});
}
replace(fragment);
el.appendChild(fragment);
}
初始化 Vue 实例
整合核心模块创建构造函数:
class Vue {
constructor(options) {
this.$options = options;
this.$data = options.data;
this.observe(this.$data);
compile(options.el, this);
}
observe(data) {
Object.keys(data).forEach(key => {
defineReactive(data, key, data[key]);
Object.defineProperty(this, key, {
get() { return data[key]; },
set(newVal) { data[key] = newVal; }
});
});
}
}
示例用法
<div id="app">{{ message }}</div>
<script>
const vm = new Vue({
el: '#app',
data: { message: 'Hello Vue!' }
});
setTimeout(() => {
vm.message = 'Updated!'; // 视图自动更新
}, 1000);
</script>
扩展方向
-
虚拟 DOM
实现patch函数对比新旧 VNode,提升渲染性能。
-
指令系统
支持v-model、v-for等指令,例如通过扩展compile函数解析指令。 -
生命周期钩子
在特定阶段触发created、mounted等回调函数。 -
组件化
通过Vue.component注册组件,支持嵌套和 props 通信。
该实现省略了错误处理和边缘情况,实际 Vue 源码包含更复杂的优化和兼容性处理。






