当前位置:首页 > VUE

使用vue实现mvvm框架

2026-02-24 17:48:04VUE

Vue 实现 MVVM 框架的核心原理

Vue 的 MVVM(Model-View-ViewModel)实现主要依赖数据绑定和响应式系统。以下是关键实现步骤:

数据劫持(响应式核心)

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

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(观察者):

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

class Watcher {
  constructor(vm, exp, cb) {
    this.vm = vm;
    this.exp = exp;
    this.cb = cb;
    this.value = this.get();
  }
  get() {
    Dep.target = this;
    const value = this.vm.data[this.exp];
    Dep.target = null;
    return value;
  }
  update() {
    const newVal = this.vm.data[this.exp];
    if (this.value !== newVal) {
      this.value = newVal;
      this.cb.call(this.vm, newVal);
    }
  }
}

模板编译

实现简易模板编译器:

function compile(node, vm) {
  if (node.nodeType === 1) {
    Array.from(node.attributes).forEach(attr => {
      if (attr.name.startsWith('v-')) {
        const exp = attr.value;
        new Watcher(vm, exp, value => {
          node.value = value;
        });
        node.addEventListener('input', e => {
          vm.data[exp] = e.target.value;
        });
      }
    });
  } else if (node.nodeType === 3) {
    const reg = /\{\{(.*)\}\}/;
    const match = node.nodeValue.match(reg);
    if (match) {
      const exp = match[1].trim();
      new Watcher(vm, exp, value => {
        node.nodeValue = value;
      });
    }
  }
  Array.from(node.childNodes).forEach(child => {
    compile(child, vm);
  });
}

整合实现

创建 Vue 类整合上述功能:

class Vue {
  constructor(options) {
    this.data = options.data;
    observe(this.data);
    compile(options.el, this);
  }
}

使用示例

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

<script>
new Vue({
  el: document.getElementById('app'),
  data: {
    message: 'Hello MVVM!'
  }
});
</script>

现代改进方案

对于 Vue 3.0+ 版本,推荐使用 Proxy 替代 Object.defineProperty

使用vue实现mvvm框架

function reactive(data) {
  return new Proxy(data, {
    get(target, key) {
      const dep = getDep(target, key);
      dep.depend();
      return Reflect.get(target, key);
    },
    set(target, key, value) {
      const result = Reflect.set(target, key, value);
      const dep = getDep(target, key);
      dep.notify();
      return result;
    }
  });
}

这种实现方式解决了数组监听和嵌套对象的问题,性能更优。

标签: 框架vue
分享给朋友:

相关文章

vue实现适老化样式

vue实现适老化样式

Vue 实现适老化样式的关键方法 全局字体与字号调整 通过 CSS 变量或主题配置统一放大基础字号,建议正文不小于 18px,标题更大。在 App.vue 中设置全局样式: :root { --…

vue实现jqueryui

vue实现jqueryui

Vue 实现 jQuery UI 功能 在 Vue 项目中实现类似 jQuery UI 的功能,可以通过原生 Vue 组件或第三方库来实现。以下是几种常见 jQuery UI 功能的 Vue 替代方案…

vue实现flvvideo

vue实现flvvideo

vue-flv-player 实现 FLV 视频播放 安装依赖包 npm install flv.js vue-flv-player 基础组件引入 <template> <v…

vue实现换页

vue实现换页

Vue实现页面切换的方法 在Vue中实现页面切换通常可以通过Vue Router来完成。Vue Router是Vue.js官方的路由管理器,用于构建单页面应用(SPA)。以下是几种常见的实现方式:…

vue实现CRUD

vue实现CRUD

Vue 实现 CRUD 操作 Vue 提供了响应式数据绑定和组件化开发能力,结合后端 API 可以轻松实现 CRUD(增删改查)功能。以下是基于 Vue 3 和 Axios 的完整实现方案。 安装依…

vue实现fragment

vue实现fragment

Vue 实现 Fragment 的方法 在 Vue 中,Fragment 允许组件返回多个根节点而不需要包裹一个额外的 DOM 元素。以下是几种实现方式: 使用 Vue 3 的 <templa…