当前位置:首页 > VUE

vue watch怎么实现的

2026-02-24 15:26:23VUE

Vue 的 watch 实现原理

Vue 的 watch 功能通过响应式系统的依赖收集和触发机制实现。其核心是监听数据变化并执行回调函数。

初始化阶段

在 Vue 实例初始化时,如果选项中有 watch 配置,会调用 initWatch 方法。该方法遍历 watch 选项,为每个监听属性创建对应的 Watcher 实例。

function initWatch(vm, watch) {
  for (const key in watch) {
    const handler = watch[key];
    createWatcher(vm, key, handler);
  }
}

创建 Watcher

createWatcher 方法会根据监听属性的配置(函数、对象、字符串)创建对应的 Watcher 实例。如果是深度监听(deep: true),会递归遍历对象的所有属性进行依赖收集。

vue watch怎么实现的

function createWatcher(vm, expOrFn, handler, options) {
  if (isPlainObject(handler)) {
    options = handler;
    handler = handler.handler;
  }
  if (typeof handler === 'string') {
    handler = vm[handler];
  }
  return vm.$watch(expOrFn, handler, options);
}

依赖收集

Watcher 实例化时,会执行 get 方法触发监听属性的 getter。在 getter 中,当前 Watcher 会被添加到依赖列表中(Dep.target)。

class Watcher {
  constructor(vm, expOrFn, cb, options) {
    this.vm = vm;
    this.cb = cb;
    this.deep = !!options.deep;
    this.getter = parsePath(expOrFn);
    this.value = this.get();
  }

  get() {
    pushTarget(this);
    const value = this.getter.call(this.vm, this.vm);
    if (this.deep) traverse(value);
    popTarget();
    return value;
  }
}

触发更新

当监听的数据发生变化时,会触发 setter 通知所有依赖的 Watcher 执行 update 方法。最终调用回调函数并传入新旧值。

vue watch怎么实现的

class Watcher {
  update() {
    const oldValue = this.value;
    this.value = this.get();
    this.cb.call(this.vm, this.value, oldValue);
  }
}

深度监听实现

深度监听通过递归遍历对象的所有属性,触发每个属性的 getter 进行依赖收集。

function traverse(val) {
  if (typeof val !== 'object') return;
  for (const key in val) {
    traverse(val[key]);
  }
}

立即执行

如果配置了 immediate: true,会在 Watcher 创建后立即执行回调函数。

if (options.immediate) {
  cb.call(vm, watcher.value);
}

注销监听

调用 $watch 返回的函数可以注销监听,内部通过 Watcherteardown 方法实现。

Vue.prototype.$watch = function(expOrFn, cb, options) {
  const watcher = new Watcher(this, expOrFn, cb, options);
  return function unwatchFn() {
    watcher.teardown();
  };
};

通过以上机制,Vue 实现了高效的数据监听功能,能够精确响应数据变化并执行相应的回调逻辑。

标签: vuewatch
分享给朋友:

相关文章

vue代理实现

vue代理实现

Vue 代理实现方法 在 Vue 项目中,配置代理可以解决开发环境下的跨域问题,通常通过修改 vue.config.js 文件实现。以下是几种常见的代理配置方式: 基础代理配置 在 vue.conf…

vue scrolltop 实现

vue scrolltop 实现

实现 Vue 中的 scrollTop 在 Vue 中实现滚动到顶部功能可以通过多种方式完成,包括使用原生 JavaScript、Vue 指令或第三方库。以下是几种常见的实现方法: 使用原生 Jav…

vue实现openoffice

vue实现openoffice

Vue 中集成 OpenOffice 的实现方法 在 Vue 项目中集成 OpenOffice 通常需要通过后端服务或现有库实现文档的预览和编辑功能。以下是几种常见的实现方式: 使用 OnlyOff…

vue实现定位打卡

vue实现定位打卡

Vue 实现定位打卡功能 获取用户地理位置 使用浏览器提供的 Geolocation API 获取用户当前位置坐标。在 Vue 组件中可以通过 navigator.geolocation 调用。 m…

vue实现左右菜单

vue实现左右菜单

实现左右菜单的基本思路 使用Vue实现左右菜单通常需要两个主要组件:左侧的导航菜单和右侧的内容区域。左侧菜单用于导航,右侧区域根据菜单选择动态展示内容。 创建左侧菜单组件 左侧菜单通常是一个列表,可…

vue导航栏实现

vue导航栏实现

Vue 导航栏实现方法 基础路由配置 安装 vue-router 并配置路由表,在 router/index.js 中定义路径与组件的映射关系: import { createRouter, cre…