自实现vue
实现 Vue 的核心功能
要实现一个简化版的 Vue,需要理解其核心功能:数据响应式、模板编译、虚拟 DOM 和组件系统。以下是关键步骤的分解:
数据响应式
Vue 使用 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();
}
});
}
}
依赖收集与派发更新
通过依赖收集器(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) {
this.vm = vm;
this.key = key;
this.cb = cb;
Dep.target = this;
this.vm[this.key]; // 触发 getter,收集依赖
Dep.target = null;
}
update() {
this.cb.call(this.vm, this.vm[this.key]);
}
}
模板编译
将模板字符串解析为 AST(抽象语法树),然后生成渲染函数。
class Compiler {
constructor(el, vm) {
this.el = document.querySelector(el);
this.vm = vm;
this.compile(this.el);
}
compile(node) {
const childNodes = node.childNodes;
Array.from(childNodes).forEach(childNode => {
if (this.isElementNode(childNode)) {
this.compileElement(childNode);
} else if (this.isTextNode(childNode)) {
this.compileText(childNode);
}
if (childNode.childNodes && childNode.childNodes.length) {
this.compile(childNode);
}
});
}
isElementNode(node) {
return node.nodeType === 1;
}
isTextNode(node) {
return node.nodeType === 3;
}
compileElement(node) {
const attributes = node.attributes;
Array.from(attributes).forEach(attr => {
const attrName = attr.name;
if (this.isDirective(attrName)) {
const dir = attrName.substring(2);
const expr = attr.value;
this[dir] && this[dir](node, expr);
}
});
}
compileText(node) {
const reg = /\{\{(.+?)\}\}/;
const value = node.textContent;
if (reg.test(value)) {
const key = RegExp.$1.trim();
node.textContent = value.replace(reg, this.vm[key]);
new Watcher(this.vm, key, newVal => {
node.textContent = newVal;
});
}
}
isDirective(attrName) {
return attrName.startsWith('v-');
}
model(node, expr) {
node.value = this.vm[expr];
new Watcher(this.vm, expr, newVal => {
node.value = newVal;
});
node.addEventListener('input', e => {
this.vm[expr] = e.target.value;
});
}
}
虚拟 DOM 实现
虚拟 DOM 是对真实 DOM 的抽象表示,通过 Diff 算法高效更新视图。
class VNode {
constructor(tag, data, children, text, elm) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
this.elm = elm;
}
}
function createElement(tag, data, children) {
return new VNode(tag, data, children, undefined, undefined);
}
function createTextNode(text) {
return new VNode(undefined, undefined, undefined, text, undefined);
}
组件系统
组件是 Vue 的核心概念之一,通过递归方式实现组件树。
class Component {
constructor(options) {
this.data = options.data;
this.methods = options.methods;
this.template = options.template;
this.el = options.el;
this.init();
}
init() {
const observer = new Observer(this.data);
new Compiler(this.el, this);
}
}
整合实现
将以上功能整合为一个简易的 Vue 类。
class Vue {
constructor(options) {
this.$options = options;
this._data = options.data;
this.observer = 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;
}
});
});
}
}
使用示例
以下是如何使用自实现的 Vue:
<div id="app">
<p>{{ message }}</p>
<input v-model="message" />
</div>
<script>
const vm = new Vue({
el: '#app',
data: {
message: 'Hello, Vue!'
}
});
</script>
总结
通过实现数据响应式、依赖收集、模板编译和虚拟 DOM,可以构建一个简化版的 Vue。虽然功能不如官方 Vue 完善,但核心原理相同。进一步扩展可以添加计算属性、生命周期钩子等功能。







