当前位置:首页 > VUE

vue手动实现mvvm

2026-01-19 20:40:39VUE

Vue 手动实现 MVVM 的核心原理

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

数据劫持(响应式系统)

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

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(订阅者)实现视图更新。

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 简化数据劫持逻辑(需处理兼容性)。

vue手动实现mvvm

标签: vuemvvm
分享给朋友:

相关文章

vue实现多层评论回复

vue实现多层评论回复

Vue 实现多层评论回复 数据结构设计 多层评论通常采用嵌套结构,每个评论对象包含子评论数组。示例数据结构如下: comments: [ { id: 1, content: '…

vue实现一个标签选择

vue实现一个标签选择

Vue 标签选择组件实现 基础实现 使用 Vue 的 v-for 和 v-model 指令可以快速实现标签选择功能: <template> <div class="tag-s…

vue实现点击

vue实现点击

实现点击事件的基本方法 在Vue中实现点击事件可以通过v-on指令或@简写方式绑定。以下是常见的点击事件绑定方法: <template> <button v-on:click…

vue datepicker 实现

vue datepicker 实现

实现 Vue Datepicker 的基本方法 在 Vue 项目中实现日期选择功能,可以使用第三方库如 vue-datepicker 或 v-calendar。以下是两种常见实现方式: 安装 vu…

vue 实现blog

vue 实现blog

Vue 实现博客的基本步骤 使用 Vue 实现博客可以分为前端和后端两部分,前端使用 Vue.js 框架,后端可以选择 Node.js、Python 或其他服务端语言。以下是一个基于 Vue 的博客实…

vue 实现关闭

vue 实现关闭

Vue 实现关闭功能的方法 在Vue中实现关闭功能通常涉及组件销毁、模态框隐藏或路由跳转等场景。以下是几种常见实现方式: 销毁当前组件 使用v-if或v-show控制组件显示/隐藏,适用于局部组件:…