当前位置:首页 > 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.js 通过npm安装Vue.js是最常见的方式。确保已安装Node.js和npm,运行以下命令: npm install vue 或者使用CDN直接引入: <script src…

jq 实现 vue

jq 实现 vue

jq 实现 Vue 的核心功能 jq 是一个轻量级的 JavaScript 库,主要用于 DOM 操作和事件处理。虽然它不能完全替代 Vue,但可以通过一些技巧模拟 Vue 的核心功能,如数据绑定、事…

ssh vue 实现

ssh vue 实现

使用SSH连接Vue项目部署的服务器 在Vue项目开发或部署过程中,可能需要通过SSH连接到远程服务器进行配置或维护。以下是实现SSH连接并部署Vue项目的关键步骤: 生成SSH密钥对 在本地终端运…

实现vue datepicker

实现vue datepicker

安装依赖 使用 vue-datepicker 或第三方库如 v-calendar 或 vue2-datepicker。以 vue2-datepicker 为例: npm install vue2…

vue实现标题

vue实现标题

Vue 实现标题的方法 在Vue中实现标题可以通过多种方式,以下是几种常见的方法: 方法一:使用模板语法 在Vue组件的模板中直接使用HTML的<h1>到<h6>标签来定义…

vue实现系统

vue实现系统

Vue 实现系统的核心方法 使用 Vue.js 构建系统时,需结合其响应式特性与组件化开发模式。以下为关键实现路径: 项目初始化与工程配置 通过 Vue CLI 或 Vite 创建项目骨架,推荐选择…