js 实现vue
实现 Vue 的基本功能
使用 JavaScript 实现一个简化版的 Vue,需要核心功能包括数据响应式、模板编译和虚拟 DOM 更新。以下是一个基础实现框架:
class Vue {
constructor(options) {
this.$options = options;
this.$data = options.data();
this.$el = document.querySelector(options.el);
this.observe(this.$data);
this.compile(this.$el);
}
observe(data) {
Object.keys(data).forEach(key => {
let value = data[key];
const dep = new Dep();
Object.defineProperty(data, key, {
get() {
Dep.target && dep.addSub(Dep.target);
return value;
},
set(newVal) {
if (newVal !== value) {
value = newVal;
dep.notify();
}
}
});
});
}
compile(node) {
Array.from(node.childNodes).forEach(child => {
if (child.nodeType === 3) {
this.compileText(child);
} else if (child.nodeType === 1) {
this.compileElement(child);
if (child.childNodes.length) {
this.compile(child);
}
}
});
}
compileText(node) {
const reg = /\{\{(.*?)\}\}/g;
const text = node.textContent;
if (reg.test(text)) {
const key = RegExp.$1.trim();
node.textContent = this.$data[key];
new Watcher(this.$data, key, (val) => {
node.textContent = val;
});
}
}
compileElement(node) {
Array.from(node.attributes).forEach(attr => {
if (attr.name.startsWith('v-')) {
const dir = attr.name.substring(2);
const exp = attr.value;
if (dir === 'model') {
node.value = this.$data[exp];
node.addEventListener('input', (e) => {
this.$data[exp] = e.target.value;
});
new Watcher(this.$data, exp, (val) => {
node.value = val;
});
}
}
});
}
}
class Dep {
constructor() {
this.subs = [];
}
addSub(sub) {
this.subs.push(sub);
}
notify() {
this.subs.forEach(sub => sub.update());
}
}
class Watcher {
constructor(data, key, cb) {
Dep.target = this;
this.cb = cb;
this.key = key;
this.data = data;
this.value = data[key]; // 触发getter
Dep.target = null;
}
update() {
this.value = this.data[this.key];
this.cb(this.value);
}
}
核心实现原理
数据响应式通过 Object.defineProperty 实现,为每个数据属性创建依赖收集器(Dep)。当数据被访问时收集依赖(Watcher),数据变化时通知所有依赖更新。
模板编译通过遍历 DOM 树实现,解析双花括号文本节点和 v-model 指令节点,为每个动态绑定创建对应的 Watcher 实例。

使用示例
<div id="app">
<input v-model="message">
<p>{{ message }}</p>
</div>
<script>
const app = new Vue({
el: '#app',
data() {
return {
message: 'Hello Vue!'
};
}
});
</script>
功能扩展方向
- 实现计算属性(computed)
- 添加方法(methods)支持
- 实现生命周期钩子
- 支持组件系统
- 实现虚拟 DOM 和 diff 算法
这个实现展示了 Vue 最核心的响应式原理和模板编译机制,实际 Vue 源码更加复杂和完善,包含更多优化和功能特性。






