答案:通过Proxy实现数据响应式,Compiler解析模板指令,Watcher与Dep完成依赖收集和视图更新,构建极简MVVM框架。

要实现一个简单的MVVM(Model-View-ViewModel)框架,核心是数据绑定和响应式更新视图。我们可以通过JavaScript的Object.defineProperty或Proxy来监听数据变化,并在变化时自动更新DOM。下面是一个极简但完整的MVVM框架示例,帮助你理解其基本原理。
使用Proxy拦截对象属性的读取和赋值操作,当数据变化时通知依赖更新。
function observe(data) {
if (typeof data !== 'object' || data === null) return data;
return new Proxy(data, {
get(target, key, receiver) {
const value = Reflect.get(target, key, receiver);
// 收集依赖(此处简化,实际可用Dep类管理)
console.log(`获取 ${key}:`, value);
return value;
},
set(target, key, value, receiver) {
const oldValue = target[key];
const result = Reflect.set(target, key, value, receiver);
if (oldValue !== value) {
console.log(`更新 ${key} 从 ${oldValue} 到 ${value}`);
dep.notify(); // 触发视图更新
}
return result;
}
});
}
遍历DOM节点,识别v-model、{{ }}等语法,并建立数据绑定。
class Compiler {
constructor(el, vm) {
this.el = document.querySelector(el);
this.vm = vm;
this.compile(this.el);
}
compile(node) {
if (node.nodeType === 1) { // 元素节点
Array.from(node.attributes).forEach(attr => {
const attrName = attr.name;
const exp = attr.value;
if (attrName.startsWith('v-model')) {
node.value = this.vm[exp];
node.addEventListener('input', e => {
this.vm[exp] = e.target.value;
});
// 添加依赖
new Watcher(this.vm, exp, value => {
node.value = value;
});
}
});
}
if (node.nodeType === 3 && /\{\{(.*)\}\}/.test(node.textContent)) { // 文本节点
const exp = RegExp.$1.trim();
node.textContent = node.textContent.replace(/\{\{(.*)\}\}/, this.vm[exp]);
new Watcher(this.vm, exp, value => {
node.textContent = value;
});
}
if (node.childNodes && node.childNodes.length) {
Array.from(node.childNodes).forEach(child => this.compile(child));
}
}
}
Watcher用于观察某个表达式的值,当值变化时执行回调。Dep是依赖管理器,负责收集Watcher并通知更新。
立即学习“Java免费学习笔记(深入)”;
class Dep {
constructor() {
this.subs = [];
}
addSub(watcher) {
this.subs.push(watcher);
}
notify() {
this.subs.forEach(watcher => watcher.update());
}
}
// 全局变量,用于临时存储当前正在求值的Watcher
let currentWatcher = null;
class Watcher {
constructor(vm, exp, cb) {
this.vm = vm;
this.exp = exp;
this.cb = cb;
this.value = this.get(); // 初始化时触发getter,完成依赖收集
}
get() {
currentWatcher = this;
const value = this.vm[this.exp]; // 触发getter
currentWatcher = null;
return value;
}
update() {
const newValue = this.vm[this.exp];
if (newValue !== this.value) {
this.cb(newValue);
}
}
}
// 修改observe中的set逻辑以支持dep
const dep = new Dep(); // 简化处理,实际应为每个属性创建独立dep
将以上模块组合成一个可用的MVVM构造函数。
class TinyMVVM {
constructor(options) {
this.$data = options.data();
this.$el = options.el;
// 响应式化数据
this.$data = observe(this.$data);
// 数据代理到实例上,方便this.xxx访问
Object.keys(this.$data).forEach(key => {
this.proxyData(key);
});
// 编译模板
new Compiler(this.$el, this);
}
proxyData(key) {
Object.defineProperty(this, key, {
get() {
return this.$data[key];
},
set(newVal) {
this.$data[key] = newVal;
}
});
}
}
现在你可以这样使用这个简易MVVM:
<div id="app">
<input v-model="message" />
<p>{{ message }}</p>
</div>
<script>
const vm = new TinyMVVM({
el: '#app',
data() {
return {
message: 'Hello MVVM!'
};
}
});
</script>
输入框内容变化时,<p>标签也会同步更新,实现了双向绑定。
基本上就这些。虽然这个框架非常基础,但它涵盖了MVVM的核心思想:响应式数据、模板编译、依赖追踪和自动更新。你可以在此基础上扩展更多功能,比如事件绑定(v-on)、计算属性、生命周期钩子等。
以上就是使用JavaScript实现一个简单的MVVM框架_javascript框架的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号