原生js实现vue
使用原生 JavaScript 实现 Vue 的核心功能
Vue 的核心功能包括数据绑定、模板渲染、响应式系统和事件处理。以下是实现这些功能的关键步骤。
数据绑定与响应式系统
通过 Object.defineProperty 或 Proxy 实现数据的响应式监听。以下是一个基于 Object.defineProperty 的简单实现:
function defineReactive(obj, key, val) {
const dep = new Dep();
Object.defineProperty(obj, key, {
get() {
if (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());
}
}
模板编译与渲染
实现一个简单的模板编译器,将模板中的插值表达式(如 {{data}})替换为实际数据:

class Compiler {
constructor(el, vm) {
this.$vm = vm;
this.$el = document.querySelector(el);
if (this.$el) {
this.compile(this.$el);
}
}
compile(node) {
const childNodes = node.childNodes;
Array.from(childNodes).forEach(child => {
if (this.isElement(child)) {
this.compileElement(child);
} else if (this.isInterpolation(child)) {
this.compileText(child);
}
if (child.childNodes && child.childNodes.length > 0) {
this.compile(child);
}
});
}
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');
}
update(node, exp, dir) {
const updater = dir + 'Updater';
this[updater] && this[updater](node, this.$vm[exp]);
new Watcher(this.$vm, exp, value => {
this[updater] && this[updater](node, value);
});
}
textUpdater(node, value) {
node.textContent = value;
}
}
观察者模式
实现 Watcher 类,用于监听数据变化并更新视图:
class Watcher {
constructor(vm, exp, cb) {
this.$vm = vm;
this.exp = exp;
this.cb = cb;
Dep.target = this;
this.value = vm[exp];
Dep.target = null;
}
update() {
const oldValue = this.value;
this.value = this.$vm[this.exp];
this.cb.call(this.$vm, this.value, oldValue);
}
}
主框架整合
将上述功能整合为一个简单的 Vue 类:

class Vue {
constructor(options) {
this.$options = options;
this.$data = options.data();
this.observe(this.$data);
new Compiler(options.el, this);
}
observe(data) {
Object.keys(data).forEach(key => {
defineReactive(this, key, data[key]);
});
}
}
使用方法
以下是如何使用这个简易 Vue 实现的示例:
<div id="app">
<p>{{ message }}</p>
</div>
<script>
const app = new Vue({
el: '#app',
data() {
return {
message: 'Hello, Vue!'
};
}
});
</script>
实现双向绑定
扩展功能以实现 v-model 双向绑定:
// 在 Compiler 类中添加对 v-model 的处理
compileElement(node) {
const attrs = node.attributes;
Array.from(attrs).forEach(attr => {
const attrName = attr.name;
const exp = attr.value;
if (attrName === 'v-model') {
this.bindModel(node, exp);
}
});
}
bindModel(node, exp) {
node.value = this.$vm[exp];
node.addEventListener('input', e => {
this.$vm[exp] = e.target.value;
});
new Watcher(this.$vm, exp, value => {
node.value = value;
});
}
注意事项
- 这只是 Vue 核心功能的简化实现,实际 Vue 源码更复杂,包含虚拟 DOM、组件系统等。
- 现代 Vue 3 使用
Proxy代替Object.defineProperty实现响应式系统,性能更好。 - 完整实现还需处理数组变化检测、生命周期钩子、计算属性等功能。






