js 实现vue
实现 Vue 的核心功能
在 JavaScript 中实现 Vue 的核心功能需要模拟数据绑定、虚拟 DOM 和响应式系统。以下是一个简化版的实现思路:
响应式系统
通过 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();
}
});
}
}
依赖收集
实现一个简单的发布-订阅模式来管理依赖。
class Dep {
constructor() {
this.subs = [];
}
addSub(sub) {
this.subs.push(sub);
}
notify() {
this.subs.forEach(sub => sub.update());
}
}
Dep.target = null;
虚拟 DOM 与渲染
实现一个简单的虚拟 DOM 和渲染函数。

class VNode {
constructor(tag, data, children, text) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
}
}
function render(vnode, container) {
const el = document.createElement(vnode.tag);
for (const key in vnode.data) {
el.setAttribute(key, vnode.data[key]);
}
if (vnode.text) {
el.textContent = vnode.text;
} else if (vnode.children) {
vnode.children.forEach(child => {
render(child, el);
});
}
container.appendChild(el);
}
组件系统
实现一个简单的组件系统,将模板、数据和方法封装在一起。
class Vue {
constructor(options) {
this.$options = options;
this._data = options.data();
new Observer(this._data);
this.compile(options.el);
}
compile(el) {
const element = document.querySelector(el);
this.compileNode(element);
}
compileNode(node) {
if (node.nodeType === 1) {
Array.from(node.attributes).forEach(attr => {
if (attr.name.startsWith('v-')) {
const dir = attr.name.substring(2);
this[dir](node, attr.value);
}
});
node.childNodes.forEach(child => this.compileNode(child));
} else if (node.nodeType === 3) {
const reg = /\{\{(.*?)\}\}/g;
const text = node.textContent;
if (reg.test(text)) {
const key = RegExp.$1.trim();
new Watcher(this._data, key, (newVal) => {
node.textContent = text.replace(reg, newVal);
});
node.textContent = text.replace(reg, this._data[key]);
}
}
}
model(node, key) {
node.value = this._data[key];
new Watcher(this._data, key, (newVal) => {
node.value = newVal;
});
node.addEventListener('input', (e) => {
this._data[key] = e.target.value;
});
}
}
Watcher 实现
Watcher 用于连接响应式数据和视图更新。
class Watcher {
constructor(data, key, cb) {
this.cb = cb;
Dep.target = this;
this.value = data[key];
Dep.target = null;
}
update() {
this.cb(this.value);
}
}
使用示例
<div id="app">
<input v-model="message">
<p>{{ message }}</p>
</div>
<script>
const app = new Vue({
el: '#app',
data() {
return {
message: 'Hello Vue'
};
}
});
</script>
实现要点
- 数据劫持:使用
Object.defineProperty或Proxy监听数据变化。 - 依赖收集:通过
Dep和Watcher管理依赖关系。 - 模板编译:解析模板中的指令和插值表达式,绑定数据和事件。
- 虚拟 DOM:简化版的虚拟 DOM 实现,用于高效更新视图。
以上代码展示了 Vue 的核心功能实现,包括响应式数据、模板编译和虚拟 DOM。实际 Vue 的实现更为复杂,包含更多优化和功能。






