当前位置:首页 > VUE

vue手动实现mvvm

2026-01-19 20:40:39VUE

Vue 手动实现 MVVM 的核心原理

MVVM(Model-View-ViewModel)的核心是数据绑定和响应式系统,Vue 通过数据劫持和发布-订阅模式实现。以下是关键实现步骤:

数据劫持(响应式系统)

使用 Object.definePropertyProxy 拦截数据的读写操作,在属性变化时触发更新。

vue手动实现mvvm

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); // 收集当前 Watcher
        return val;
      },
      set(newVal) {
        if (newVal === val) return;
        val = newVal;
        dep.notify(); // 通知所有 Watcher 更新
      }
    });
  }
}

依赖收集与发布订阅

通过 Dep(依赖管理器)和 Watcher(订阅者)实现视图更新。

vue手动实现mvvm

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; // 标记当前 Watcher
    this.oldValue = vm[key]; // 触发 getter 收集依赖
    Dep.target = null;
  }
  update() {
    const newValue = this.vm[this.key];
    if (newValue !== this.oldValue) {
      this.cb(newValue);
    }
  }
}

模板编译

将模板中的插值表达式和指令解析为数据绑定的逻辑。

class Compiler {
  constructor(el, vm) {
    this.vm = vm;
    this.el = document.querySelector(el);
    this.compile(this.el);
  }

  compile(node) {
    Array.from(node.childNodes).forEach(child => {
      if (this.isTextNode(child)) {
        this.compileText(child);
      } else if (this.isElementNode(child)) {
        this.compileElement(child);
      }
      if (child.childNodes?.length) {
        this.compile(child);
      }
    });
  }

  compileText(node) {
    const reg = /\{\{(.*?)\}\}/g;
    const text = node.textContent;
    if (reg.test(text)) {
      const key = RegExp.$1.trim();
      node.textContent = text.replace(reg, this.vm[key]);
      new Watcher(this.vm, key, val => {
        node.textContent = text.replace(reg, val);
      });
    }
  }
}

整合 MVVM 入口

将以上模块组合成完整的 MVVM 框架。

class MVVM {
  constructor(options) {
    this.$options = options;
    this.$data = options.data;
    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;
        }
      });
    });
  }
}

使用示例

<div id="app">{{ message }}</div>
<script>
  const vm = new MVVM({
    el: '#app',
    data: { message: 'Hello MVVM' }
  });
  setTimeout(() => {
    vm.message = 'Updated!'; // 视图自动更新
  }, 1000);
</script>

关键点说明

  • 数据劫持:通过 Object.defineProperty 监听数据变化。
  • 依赖收集:在 getter 中收集依赖,在 setter 中触发更新。
  • 模板编译:解析模板中的动态绑定,初始化视图并创建 Watcher
  • Proxy 替代方案:现代浏览器可使用 Proxy 简化数据劫持逻辑(需处理兼容性)。

标签: vuemvvm
分享给朋友:

相关文章

vue登录业务的实现

vue登录业务的实现

实现登录业务的基本流程 在Vue中实现登录业务通常涉及前端界面设计、表单验证、API请求交互、状态管理以及路由控制等环节。以下是核心实现步骤: 登录表单设计与验证 创建包含用户名和密码输入框的登录组…

vue菜单实现

vue菜单实现

Vue 菜单实现方法 使用 Element UI 的菜单组件 Element UI 提供了现成的菜单组件,适合快速实现导航菜单。安装 Element UI 后,可以直接使用 el-menu 相关组件。…

vue实现键盘

vue实现键盘

Vue 实现键盘功能 在Vue中实现键盘功能通常涉及监听键盘事件、处理输入以及渲染虚拟键盘界面。以下是几种常见的实现方式: 监听键盘事件 通过@keydown或@keyup指令监听键盘事件,适用于需…

vue实现购票

vue实现购票

Vue 实现购票功能 数据结构设计 购票功能通常需要以下数据结构: 场次信息(时间、地点、价格) 座位信息(可选座位、已售座位) 用户订单信息 示例数据结构: data() { return…

实现vue cli

实现vue cli

安装 Vue CLI 确保系统中已安装 Node.js(版本建议 12.x 或更高)。通过 npm 全局安装 Vue CLI: npm install -g @vue/cli 安装完成后验证版本:…

vue cli 实现

vue cli 实现

Vue CLI 实现步骤 安装 Vue CLI 确保 Node.js 版本在 8.9 或以上。通过 npm 全局安装 Vue CLI: npm install -g @vue/cli 创建新项目 使…