当前位置:首页 > VUE

vue 响应式实现

2026-01-15 06:03:26VUE

Vue 响应式实现原理

Vue 的响应式系统通过数据劫持结合发布-订阅模式实现,核心是 Object.defineProperty(Vue 2.x)或 Proxy(Vue 3.x)。

数据劫持(Vue 2.x)

Vue 2.x 使用 Object.defineProperty 递归遍历对象的属性,将其转换为 getter/setter:

function defineReactive(obj, key, val) {
  Object.defineProperty(obj, key, {
    get() {
      console.log(`读取 ${key}: ${val}`);
      return val;
    },
    set(newVal) {
      if (newVal !== val) {
        console.log(`设置 ${key}: ${newVal}`);
        val = newVal;
        // 触发更新
      }
    }
  });
}

依赖收集与派发更新

每个响应式属性关联一个 Dep(依赖管理器),在 getter 中收集依赖(Watcher),在 setter 中通知更新:

class Dep {
  constructor() {
    this.subs = new Set();
  }
  addSub(watcher) {
    this.subs.add(watcher);
  }
  notify() {
    this.subs.forEach(watcher => watcher.update());
  }
}

// Watcher 示例
class Watcher {
  update() {
    console.log('视图更新');
  }
}

Vue 3.x 的 Proxy 实现

Vue 3.x 改用 Proxy 实现更高效的响应式:

function reactive(obj) {
  return new Proxy(obj, {
    get(target, key) {
      track(target, key); // 依赖收集
      return Reflect.get(target, key);
    },
    set(target, key, value) {
      Reflect.set(target, key, value);
      trigger(target, key); // 触发更新
    }
  });
}

数组响应式处理

Vue 2.x 通过重写数组的变异方法(如 pushpop)实现响应式:

vue 响应式实现

const arrayProto = Array.prototype;
const arrayMethods = Object.create(arrayProto);
['push', 'pop'].forEach(method => {
  const original = arrayProto[method];
  arrayMethods[method] = function(...args) {
    const result = original.apply(this, args);
    // 触发更新逻辑
    return result;
  };
});

响应式系统的局限性

  • 对象属性添加/删除:Vue 2.x 需通过 Vue.set/Vue.delete 触发响应。
  • 数组索引修改:直接通过索引修改元素(如 arr[0] = newVal)不会触发更新。
  • Proxy 兼容性:Vue 3.x 的 Proxy 不支持 IE11 及以下浏览器。

性能优化建议

  • 避免频繁操作大型响应式对象。
  • 使用 Object.freeze() 冻结不需要响应式的数据。
  • 在 Vue 3.x 中,通过 shallowRefshallowReactive 减少深层响应式开销。

以上实现展示了 Vue 响应式系统的核心逻辑,实际源码中还包含虚拟 DOM 比对、批量异步更新等优化策略。

标签: vue
分享给朋友:

相关文章

vue实现贴图

vue实现贴图

Vue 实现贴图功能 在Vue中实现贴图功能通常涉及将图片动态添加到指定位置或元素上。以下是几种常见实现方式: 使用v-bind动态绑定图片 通过数据驱动的方式动态更换图片源: <templ…

vue实现效果

vue实现效果

以下是Vue实现常见效果的几种典型方法,分为不同场景说明: 数据绑定与响应式更新 使用v-model实现表单双向绑定: <template> <input v-model="…

vue实现jqueryui

vue实现jqueryui

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

vue实现定位

vue实现定位

Vue 中实现定位的方法 在 Vue 中实现定位可以通过以下几种方式: 使用 CSS 定位 通过 CSS 的 position 属性实现定位,Vue 中可以直接在组件的 <style>…

vue实现oauth

vue实现oauth

Vue 实现 OAuth 的步骤 安装必要的依赖 确保项目中安装了 axios 和 vue-router。OAuth 通常需要发送 HTTP 请求和处理路由跳转。 npm install axios…

vue实现逻辑

vue实现逻辑

Vue 实现逻辑的核心概念 Vue.js 是一个渐进式 JavaScript 框架,其核心逻辑围绕数据驱动和组件化开发。通过响应式系统、虚拟 DOM 和组件生命周期等机制,Vue 实现了高效的前端开发…