js 实现vue模板
使用 JavaScript 实现 Vue 模板
在 JavaScript 中实现类似 Vue 的模板功能,可以通过以下方法完成。Vue 的核心是数据绑定和模板渲染,以下是一个简化版的实现。
数据绑定与响应式系统
通过 Object.defineProperty 或 Proxy 实现数据劫持,监听数据变化并更新视图。
class Vue {
constructor(options) {
this.$data = options.data();
this.$el = document.querySelector(options.el);
this.observe(this.$data);
this.compile(this.$el);
}
observe(data) {
if (!data || typeof data !== 'object') return;
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) return;
value = newVal;
dep.notify();
}
});
this.observe(value);
});
}
compile(node) {
[...node.childNodes].forEach(child => {
if (child.nodeType === 3) { // 文本节点
const text = child.textContent;
const reg = /\{\{\s*(\S+)\s*\}\}/;
if (reg.test(text)) {
const key = RegExp.$1.trim();
new Watcher(this.$data, key, (val) => {
child.textContent = text.replace(reg, val);
});
}
} else if (child.nodeType === 1) { // 元素节点
this.compile(child);
}
});
}
}
class Dep {
constructor() {
this.subs = [];
}
addSub(sub) {
this.subs.push(sub);
}
notify() {
this.subs.forEach(sub => sub.update());
}
}
class Watcher {
constructor(data, key, cb) {
this.cb = cb;
Dep.target = this;
this.value = data[key]; // 触发 getter
Dep.target = null;
}
update() {
this.cb(this.value);
}
}
模板语法支持
实现类似 Vue 的 {{ }} 插值语法,通过正则匹配替换数据。
// 示例用法
const app = new Vue({
el: '#app',
data() {
return {
message: 'Hello, Vue!'
};
}
});
指令系统
扩展指令功能,如 v-model 实现双向绑定。
// 在 compile 方法中添加指令处理
if (child.nodeType === 1) {
[...child.attributes].forEach(attr => {
if (attr.name === 'v-model') {
const key = attr.value;
child.value = this.$data[key];
child.addEventListener('input', (e) => {
this.$data[key] = e.target.value;
});
new Watcher(this.$data, key, (val) => {
child.value = val;
});
}
});
this.compile(child);
}
虚拟 DOM 优化
引入虚拟 DOM 减少直接操作真实 DOM 的开销。
class VNode {
constructor(tag, data, children, text) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
}
}
function createVNode(tag, data, children) {
return new VNode(tag, data, children, null);
}
function createTextVNode(text) {
return new VNode(null, null, null, text);
}
function patch(oldVNode, newVNode) {
// 实现 DOM 更新逻辑
}
通过以上方法,可以实现一个简化版的 Vue 模板功能,包括数据绑定、模板渲染和指令系统。







