当前位置:首页 > VUE

vue响应式实现机制

2026-02-23 18:33:04VUE

Vue 响应式实现机制

Vue 的响应式系统通过数据劫持和依赖收集实现,核心基于 Object.defineProperty(Vue 2)或 Proxy(Vue 3)。以下是具体实现机制:

数据劫持

Vue 2 使用 Object.defineProperty 劫持对象的属性访问和修改。通过定义 gettersetter,在属性被访问或修改时触发依赖更新。

// Vue 2 数据劫持简化示例
function defineReactive(obj, key, val) {
  Object.defineProperty(obj, key, {
    get() {
      console.log('get', key);
      return val;
    },
    set(newVal) {
      if (newVal !== val) {
        console.log('set', key);
        val = newVal;
      }
    }
  });
}

Vue 3 改用 Proxy 代理整个对象,能直接监听对象增删和数组变化,无需递归遍历属性。

// Vue 3 Proxy 示例
const reactive = (target) => {
  return new Proxy(target, {
    get(target, key, receiver) {
      console.log('get', key);
      return Reflect.get(target, key, receiver);
    },
    set(target, key, value, receiver) {
      console.log('set', key);
      return Reflect.set(target, key, value, receiver);
    }
  });
};

依赖收集

每个响应式数据关联一个 Dep 实例(依赖管理器),在 getter 中收集当前正在执行的 Watcher(依赖),在 setter 中通知所有 Watcher 更新。

class Dep {
  constructor() {
    this.subscribers = new Set();
  }
  depend() {
    if (activeWatcher) this.subscribers.add(activeWatcher);
  }
  notify() {
    this.subscribers.forEach(watcher => watcher.update());
  }
}

let activeWatcher = null;
class Watcher {
  constructor(updateFn) {
    this.updateFn = updateFn;
    this.update();
  }
  update() {
    activeWatcher = this;
    this.updateFn();
    activeWatcher = null;
  }
}

虚拟 DOM 与批量更新

数据变化触发 Watcher 更新后,Vue 通过异步队列(nextTick)批量处理 DOM 更新,避免重复渲染。虚拟 DOM 差异比对(diff 算法)最小化真实 DOM 操作。

数组响应式处理

Vue 2 通过重写数组的 pushpop 等方法实现响应式,内部调用 ob.dep.notify() 通知更新。Vue 3 的 Proxy 可直接监听数组索引变化。

vue响应式实现机制

// Vue 2 数组劫持示例
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);
    this.__ob__.dep.notify();
    return result;
  };
});

总结

  • Vue 2:基于 Object.defineProperty + Dep/Watcher,需递归遍历对象且对数组特殊处理。
  • Vue 3:基于 Proxy + effect(类似 Watcher),支持原生对象和数组操作,性能更优。

标签: 机制vue
分享给朋友:

相关文章

vue页面实现

vue页面实现

Vue 页面实现方法 创建 Vue 组件 使用 Vue 单文件组件(SFC)方式创建页面,文件扩展名为 .vue。一个基本的 Vue 组件包含三个部分:模板(template)、脚本(script)和…

vue实现图册

vue实现图册

Vue实现图册功能 在Vue中实现图册功能通常涉及图片展示、切换、缩放等交互效果。以下是常见的实现方法和关键代码示例: 基础图册组件结构 使用Vue单文件组件构建基础结构: <templat…

vue 实现轮播

vue 实现轮播

Vue 实现轮播的方法 使用第三方库(如 Swiper) 安装 Swiper 库: npm install swiper 在 Vue 组件中引入 Swiper: <template>…

vue实现通讯

vue实现通讯

Vue 组件通讯方法 父子组件通讯 父组件向子组件传递数据通过 props,子组件向父组件传递数据通过 $emit 事件。 父组件模板: <child-component :message=…

vue实现甘特图

vue实现甘特图

使用 Vue 实现甘特图 基于开源库(如 vue-ganttastic) 安装依赖库: npm install vue-ganttastic 示例代码: <template> &l…

实现简单vue

实现简单vue

实现一个简单的 Vue.js 框架 Vue.js 的核心功能包括数据绑定、响应式系统和虚拟 DOM。以下是一个简化版的 Vue 实现,涵盖基本功能。 数据响应式系统 使用 Object.define…