当前位置:首页 > 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实现socket

vue实现socket

Vue 中实现 WebSocket 通信 在 Vue 项目中实现 WebSocket 通信可以通过原生 WebSocket API 或第三方库(如 socket.io-client)完成。以下是两种常…

vue实现试卷

vue实现试卷

Vue实现试卷系统的基本思路 使用Vue.js构建试卷系统需要结合组件化开发、状态管理和后端数据交互。核心功能包括题目展示、答题逻辑、计时器和提交答案。 核心功能模块划分 试卷组件结构 试卷容器组…

vue nexttrick实现

vue nexttrick实现

Vue 中 nextTick 的实现原理 nextTick 是 Vue 提供的一个异步方法,用于在下次 DOM 更新循环结束之后执行延迟回调。它利用了 JavaScript 的事件循环机制,确保回调在…

vue实现gridlayout

vue实现gridlayout

Vue 实现 Grid Layout 使用 CSS Grid 布局 CSS Grid 是一种强大的布局系统,可以直接在 Vue 组件的样式中使用。通过定义网格容器和网格项,可以快速实现复杂的布局结构。…

vue实现气泡

vue实现气泡

Vue 实现气泡效果的方法 在 Vue 中实现气泡效果可以通过 CSS 动画、第三方库或自定义组件完成。以下是几种常见实现方式: 使用纯 CSS 和 Vue 过渡 通过 Vue 的过渡系统结合 CS…

vue实现烟花

vue实现烟花

Vue 实现烟花效果 在 Vue 中实现烟花效果可以通过结合 CSS 动画和 JavaScript 动态生成烟花元素。以下是具体实现方法: 动态生成烟花元素 通过 Vue 的 v-for 动…