vue实现mvvm
Vue 实现 MVVM 模式
MVVM(Model-View-ViewModel)是一种前端架构模式,Vue 是其典型实现之一。MVVM 的核心是通过数据绑定和响应式系统实现视图与数据的自动同步。
数据绑定与响应式原理
Vue 通过 Object.defineProperty 或 Proxy 实现数据的响应式。当数据变化时,视图自动更新。
// 示例:Vue 2.x 使用 Object.defineProperty
function defineReactive(obj, key, val) {
Object.defineProperty(obj, key, {
get() {
return val;
},
set(newVal) {
if (newVal !== val) {
val = newVal;
console.log(`属性 ${key} 更新为 ${newVal}`);
}
}
});
}
模板编译与虚拟 DOM
Vue 将模板编译为渲染函数,生成虚拟 DOM。当数据变化时,通过 Diff 算法比对虚拟 DOM 并高效更新真实 DOM。
// 示例:模板编译为渲染函数
const template = `<div>{{ message }}</div>`;
const render = new Function('with(this){return _c("div",[_v(_s(message))])}');
双向数据绑定
通过 v-model 实现表单元素与数据的双向绑定,本质是语法糖。
<input v-model="message">
<!-- 等价于 -->
<input :value="message" @input="message = $event.target.value">
依赖收集与派发更新
Vue 通过 Watcher 和 Dep 实现依赖收集。每个响应式属性有一个 Dep 实例,Watcher 在求值过程中触发属性的 getter,从而将 Watcher 添加到 Dep 中。
class Dep {
constructor() {
this.subs = [];
}
addSub(sub) {
this.subs.push(sub);
}
notify() {
this.subs.forEach(sub => sub.update());
}
}
实现简易 Vue 类
以下是一个简化版的 Vue 实现:
class Vue {
constructor(options) {
this.$options = options;
this._data = options.data;
this.observe(this._data);
this.compile(options.el);
}
observe(data) {
Object.keys(data).forEach(key => {
let value = data[key];
const dep = new Dep();
Object.defineProperty(data, key, {
get() {
if (Dep.target) {
dep.addSub(Dep.target);
}
return value;
},
set(newVal) {
if (newVal !== value) {
value = newVal;
dep.notify();
}
}
});
});
}
compile(el) {
const element = document.querySelector(el);
this.compileNode(element);
}
compileNode(node) {
if (node.nodeType === 1) {
Array.from(node.attributes).forEach(attr => {
if (attr.name.startsWith('v-')) {
const dir = attr.name.substring(2);
new Watcher(this, node, dir, attr.value);
}
});
}
if (node.childNodes.length > 0) {
node.childNodes.forEach(child => this.compileNode(child));
}
}
}
总结
Vue 实现 MVVM 主要通过响应式系统、模板编译和虚拟 DOM 技术。数据变化自动触发视图更新,开发者只需关注数据逻辑,无需手动操作 DOM。







