当前位置:首页 > VUE

vue实现mvvm

2026-01-08 00:42:20VUE

Vue 实现 MVVM 模式

MVVM(Model-View-ViewModel)是一种前端架构模式,Vue 是其典型实现之一。MVVM 的核心是通过数据绑定和响应式系统实现视图与数据的自动同步。

数据绑定与响应式原理

Vue 通过 Object.definePropertyProxy 实现数据的响应式。当数据变化时,视图自动更新。

// 示例: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。

vue实现mvvm

标签: vuemvvm
分享给朋友:

相关文章

vue实现分页

vue实现分页

Vue实现分页的方法 使用Element UI的分页组件 Element UI提供了现成的分页组件el-pagination,可以快速实现分页功能。 <template> &…

vue实现anchor

vue实现anchor

Vue 实现 Anchor(锚点)功能 在 Vue 中实现锚点功能可以通过多种方式完成,以下是几种常见的方法: 使用 HTML 原生锚点 HTML 原生锚点是最简单的方式,通过 <a>…

vue实现密码

vue实现密码

Vue 密码输入组件实现 基础密码输入框实现 使用 Vue 的 v-model 指令绑定数据,并通过 type="password" 设置输入类型为密码: <template>…

vue实现预约页面

vue实现预约页面

Vue 预约页面实现步骤 准备工作 安装Vue CLI创建项目,确保已配置好开发环境。使用vue create appointment-page初始化项目,选择默认配置或手动配置。 页面结构设计…

vue实现年历

vue实现年历

Vue 实现年历的方法 使用 Vue 实现年历可以通过组件化开发方式,结合日期计算和动态渲染完成。以下是两种常见的实现方式: 基于原生 Vue 的日历组件 创建 Calendar.vue 组件文件…

vue的动画实现

vue的动画实现

Vue 动画实现方式 Vue 提供了多种方式实现动画效果,主要通过内置组件和第三方库支持。 使用 Vue 内置过渡组件 Vue 的 transition 和 transition-group 组件可…