当前位置:首页 > VUE

vue手动实现mvvm

2026-02-20 12:45:52VUE

Vue 手动实现 MVVM 的核心思路

MVVM(Model-View-ViewModel)的核心是数据绑定和视图自动更新。以下是手动实现的关键步骤:

数据劫持(响应式数据)

通过 Object.definePropertyProxy 监听数据变化:

vue手动实现mvvm

function observe(data) {
  if (!data || typeof data !== 'object') return;
  Object.keys(data).forEach(key => {
    let value = data[key];
    const dep = new Dep();
    observe(value);
    Object.defineProperty(data, key, {
      get() {
        Dep.target && dep.addSub(Dep.target);
        return value;
      },
      set(newVal) {
        if (newVal === value) return;
        value = newVal;
        observe(newVal);
        dep.notify();
      }
    });
  });
}

依赖收集(Dep 类)

管理订阅者(Watcher)的依赖关系:

vue手动实现mvvm

class Dep {
  constructor() {
    this.subs = [];
  }
  addSub(sub) {
    this.subs.push(sub);
  }
  notify() {
    this.subs.forEach(sub => sub.update());
  }
}
Dep.target = null;

观察者(Watcher 类)

更新视图的具体实现:

class Watcher {
  constructor(vm, key, cb) {
    this.vm = vm;
    this.key = key;
    this.cb = cb;
    Dep.target = this;
    this.vm[this.key]; // 触发 getter
    Dep.target = null;
  }
  update() {
    this.cb.call(this.vm, this.vm[this.key]);
  }
}

模板编译(Compiler)

解析 DOM 并绑定数据:

class Compiler {
  constructor(el, vm) {
    this.vm = vm;
    this.el = document.querySelector(el);
    this.compile(this.el);
  }
  compile(node) {
    Array.from(node.childNodes).forEach(node => {
      if (node.nodeType === 3) {
        this.compileText(node);
      } else if (node.nodeType === 1) {
        this.compileElement(node);
      }
      if (node.childNodes.length) {
        this.compile(node);
      }
    });
  }
  compileText(node) {
    const reg = /\{\{(.*?)\}\}/g;
    const text = node.textContent;
    if (reg.test(text)) {
      const key = RegExp.$1.trim();
      node.textContent = this.vm[key];
      new Watcher(this.vm, key, val => {
        node.textContent = val;
      });
    }
  }
  compileElement(node) {
    Array.from(node.attributes).forEach(attr => {
      if (attr.name.startsWith('v-')) {
        const dir = attr.name.substring(2);
        const key = attr.value;
        this[dir + 'Updater'](node, key);
      }
    });
  }
  modelUpdater(node, key) {
    node.value = this.vm[key];
    new Watcher(this.vm, key, val => {
      node.value = val;
    });
    node.addEventListener('input', e => {
      this.vm[key] = e.target.value;
    });
  }
}

整合实现 MVVM 类

class MVVM {
  constructor(options) {
    this.$options = options;
    this.$data = options.data;
    observe(this.$data);
    Object.keys(this.$data).forEach(key => {
      this.proxyData(key);
    });
    new Compiler(options.el, this);
  }
  proxyData(key) {
    Object.defineProperty(this, key, {
      get() {
        return this.$data[key];
      },
      set(newVal) {
        this.$data[key] = newVal;
      }
    });
  }
}

使用示例

<div id="app">
  <input v-model="message">
  <p>{{ message }}</p>
</div>

<script>
const vm = new MVVM({
  el: '#app',
  data: {
    message: 'Hello MVVM!'
  }
});
</script>

实现要点说明

  1. 数据劫持是响应式的核心,Vue 3 改用 Proxy 实现更完善的监听
  2. 依赖收集确保只有依赖数据的视图部分会更新
  3. 模板编译将声明式模板转换为数据绑定的具体操作
  4. 通过代理将 data 的属性直接暴露在 VM 实例上

以上实现省略了虚拟 DOM、组件系统等 Vue 的高级特性,但完整展示了 MVVM 的核心原理。

标签: vuemvvm
分享给朋友:

相关文章

vue 实现全选

vue 实现全选

Vue 实现全选功能 在 Vue 中实现全选功能通常需要结合复选框的状态管理,以下是几种常见的实现方式: 使用 v-model 绑定数组 通过 v-model 绑定一个数组来管理选中的项,全选时将…

vue实现a4打印模板

vue实现a4打印模板

使用Vue实现A4打印模板 在Vue中实现A4打印模板需要结合CSS的打印样式和Vue的模板渲染能力。以下是具体实现方法: 设置A4纸张尺寸 在CSS中定义A4纸张的标准尺寸(210mm × 29…

vue实现节流

vue实现节流

vue实现节流的方法 在Vue中实现节流(throttle)功能,通常用于限制高频事件的触发频率,例如滚动、输入或按钮点击。以下是几种常见的实现方式: 使用Lodash的throttle函数 安装L…

vue实现波形

vue实现波形

实现波形效果的方法 在Vue中实现波形效果可以通过多种方式完成,常见的方法包括使用Canvas绘制、CSS动画或第三方库。以下是几种实现方案: 使用Canvas绘制波形 通过Canvas API动…

vue 实现工具

vue 实现工具

Vue 实现工具的方法 使用 Vue 实现工具功能可以通过多种方式完成,具体取决于工具的类型和需求。以下是几种常见的方法: 组件化实现 创建一个独立的 Vue 组件来封装工具功能。例如,实现一…

vue实现gps

vue实现gps

Vue 中实现 GPS 定位功能 在 Vue 中实现 GPS 定位功能通常依赖于浏览器的 Geolocation API 或第三方地图服务(如高德、百度地图等)。以下是两种常见的实现方式: 使用浏…