当前位置:首页 > VUE

vue依赖收集的实现

2026-01-22 03:51:53VUE

Vue 依赖收集的实现原理

Vue 的依赖收集是通过响应式系统实现的,核心在于 ObserverDepWatcher 三者的协作。

响应式数据初始化

通过 Object.definePropertyProxy(Vue 3)劫持数据对象的属性访问。在 getter 中触发依赖收集,在 setter 中触发更新通知。

vue依赖收集的实现

function defineReactive(obj, key, val) {
  const dep = new Dep();
  Object.defineProperty(obj, key, {
    get() {
      if (Dep.target) {
        dep.depend(); // 收集依赖
      }
      return val;
    },
    set(newVal) {
      if (val === newVal) return;
      val = newVal;
      dep.notify(); // 触发更新
    }
  });
}

Dep 类管理依赖

Dep 是依赖管理器,每个响应式属性对应一个 Dep 实例,用于存储所有依赖该属性的 Watcher

vue依赖收集的实现

class Dep {
  constructor() {
    this.subs = []; // 存储 Watcher 实例
  }
  depend() {
    if (Dep.target) {
      this.subs.push(Dep.target); // 添加 Watcher
    }
  }
  notify() {
    this.subs.forEach(watcher => watcher.update()); // 通知更新
  }
}
Dep.target = null; // 全局唯一 Watcher 标记

Watcher 类触发依赖

Watcher 是观察者,在组件渲染或计算属性求值时被创建。它会将自身赋值给 Dep.target,触发属性的 getter 从而完成依赖收集。

class Watcher {
  constructor(vm, expOrFn, cb) {
    this.vm = vm;
    this.getter = parsePath(expOrFn);
    this.cb = cb;
    this.value = this.get();
  }
  get() {
    Dep.target = this; // 标记当前 Watcher
    const value = this.getter.call(this.vm, this.vm); // 触发 getter
    Dep.target = null; // 收集完成后清除标记
    return value;
  }
  update() {
    this.run();
  }
  run() {
    const value = this.get();
    if (value !== this.value) {
      this.cb.call(this.vm, value, this.value);
    }
  }
}

依赖收集流程

  1. 组件初始化时创建 Watcher,触发 get 方法。
  2. Dep.target 被设置为当前 Watcher
  3. 访问响应式数据时触发 getter,调用 dep.depend()Watcher 存入 subs
  4. 数据变化时触发 setter,调用 dep.notify() 通知所有 Watcher 更新。

Vue 3 的优化

Vue 3 改用 Proxy 实现响应式,依赖收集逻辑类似但更高效:

  • 通过 track 函数收集依赖(对应 depend)。
  • 通过 trigger 函数触发更新(对应 notify)。
  • 使用 WeakMapSet 存储依赖关系,避免内存泄漏。

标签: vue
分享给朋友:

相关文章

vue 实现在线预览

vue 实现在线预览

Vue 实现在线预览的常见方法 使用 iframe 嵌入 通过 iframe 标签可以嵌入多种类型的文件,如 PDF、图片、网页等。需要确保文件地址可访问。 <template>…

vue实现飘窗原理

vue实现飘窗原理

vue实现飘窗原理 飘窗效果通常指在页面上悬浮显示的弹窗或通知,跟随页面滚动或固定在某个位置。Vue实现这一效果主要依赖组件化开发、CSS定位和动态数据绑定。 组件结构设计 创建一个独立的Vue组…

vue实现一个tab栏

vue实现一个tab栏

Vue 实现 Tab 栏 基础实现(选项式 API) <template> <div class="tab-container"> <div class="t…

vue   实现单选

vue 实现单选

Vue 实现单选功能 在 Vue 中实现单选功能可以通过多种方式,以下是几种常见的方法: 使用原生 <input type="radio"> 绑定 v-model 通过 v-model…

vue tag实现

vue tag实现

Vue 标签实现方法 在 Vue 中实现标签功能可以通过多种方式完成,常见场景包括动态标签生成、标签输入框、标签管理等。以下是几种典型实现方案: 动态标签列表渲染 使用 v-for 指令渲染标签数组…

vue实现流程

vue实现流程

Vue 实现流程的基本步骤 安装 Vue.js 可以通过 CDN 引入或使用 npm/yarn 安装。 CDN 方式: <script src="https://cdn.jsdelivr…