手动实现合计vue
手动实现 Vue 的核心功能
实现一个简易的 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 节点,解析指令和插值表达式,并建立与数据的关联。
class Compiler {
constructor(el, vm) {
this.$vm = vm;
this.$el = document.querySelector(el);
this.compile(this.$el);
}
compile(el) {
const childNodes = el.childNodes;
Array.from(childNodes).forEach(node => {
if (this.isElement(node)) {
this.compileElement(node);
} else if (this.isInterpolation(node)) {
this.compileText(node);
}
if (node.childNodes && node.childNodes.length > 0) {
this.compile(node);
}
});
}
isElement(node) {
return node.nodeType === 1;
}
isInterpolation(node) {
return node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent);
}
compileElement(node) {
const attrs = node.attributes;
Array.from(attrs).forEach(attr => {
const attrName = attr.name;
const exp = attr.value;
if (this.isDirective(attrName)) {
const dir = attrName.substring(2);
this[dir] && this[dir](node, exp);
}
});
}
compileText(node) {
this.update(node, RegExp.$1, 'text');
}
isDirective(attr) {
return attr.startsWith('v-');
}
text(node, exp) {
this.update(node, exp, 'text');
}
update(node, exp, dir) {
const fn = this[dir + 'Updater'];
fn && fn(node, this.$vm[exp]);
new Watcher(this.$vm, exp, val => {
fn && fn(node, val);
});
}
textUpdater(node, value) {
node.textContent = value;
}
}
观察者模式
实现 Watcher 类,用于监听数据变化并执行更新操作。
class Watcher {
constructor(vm, key, cb) {
this.$vm = vm;
this.key = key;
this.cb = cb;
Dep.target = this;
this.$vm[key];
Dep.target = null;
}
update() {
this.cb.call(this.$vm, this.$vm[this.key]);
}
}
整合功能
将以上功能整合到一个 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: {
message: 'Hello, Vue!'
}
});
</script>
以上代码实现了一个简易的 Vue 框架,包含数据响应式、模板编译和依赖更新等核心功能。可以根据需求进一步扩展指令和功能。







