vue源码分析-响应式系统工作原理

news2024/9/29 17:58:05

上一章,我们讲到了Vue初始化做的一些操作,那么我们这一章来讲一个Vue核心概念响应式系统
我们先来看一下官方对深入响应式系统的解释:

当你把一个普通的 JavaScript 对象传给 Vue 实例的 data 选项,Vue 将遍历此对象所有的属性。
并使用 Object.defineProperty 把这些属性全部转为 getter/setter。
Object.defineProperty 是 ES5 中一个无法 shim 的特性。
这也就是为什么 Vue 不支持 IE8 以及更低版本浏览器的原因。

在这里插入图片描述

上图是Vue官方放出的一张图,而且提到核心概念Object.defineProperty,那么我们直接看源码,我们看到的Object.definePropertydefineReactive函数的内部,而defineReactive函数在walk函数内部,依次找到源头是Observer

./core/observer/index
export class Observer {
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that has this object as root $data
  /**   * 生成的Observer实例上挂载三个属性   * 1. value, 即观测数据对象本身   * 2. dep, 用于依赖收集的容器   * 3. vmCount, 直接写死为0   */
  constructor (value: any) {
    this.value = value
    this.dep = new Dep()
    this.vmCount = 0
    // 在观测数据对象上添加__ob__属性, 是Observer实例的引用
    // def相当于Object.defineProperty, 区别是dep里会把__ob__属性设置为不可枚举
    // 需要注意的是, value.__ob__.value 显然就是 value 本身, 这里有一个循环引用
    def(value, '__ob__', this)
    if (Array.isArray(value)) {
      const augment = hasProto
        ? protoAugment
        : copyAugment
      augment(value, arrayMethods, arrayKeys)
      this.observeArray(value)
    } else {
      this.walk(value)
    }
  }
  // 用于处理对象类型的观测值, 循环所有的key都调用一次defineReactive
  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i])
    }
  }
  // 对数组的每一项进行监听
  observeArray (items: Array<any>) {
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}

value是需要被观察的数据对象,在构造函数中,会给value增加ob属性,作为数据已经被Observer观察的标志。如果value数组,就使用observeArray遍历value,对value中每一个元素调用observe分别进行观察。如果value对象,则使用walk遍历value上每个key,对每个key调用defineReactive来获得该keyset/get控制权。

那么说到假如value是数组的话,调用observeArray方法遍历数组,末尾还调用了observe函数,那到底这个函数有什么用呢?我们来一探究竟:

// 用于观测一个数据
export function observe (value: any, asRootData: ?boolean): Observer | void {
  // 对于不是object或者是vnode实例的数据, 直接返回, 不会进行观测
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  let ob: Observer | void
  // 如果数据上已有__ob__属性, 说明该数据已经被观测, 不再重复处理
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    ob = value.__ob__
  // 要观测一个数据需要满足以下条件: 
  // 1. shouldObserve为true, 这是一个标志位, 默认为true, 某些特殊情况下会改成false
  // 2. !isServerRendering(), 不能是服务端渲染
  // 3. Array.isArray(value) || isPlainObject(value), 要观测的数据必须是数组或者对象
  // 4. Object.isExtensible(value). 要观测的数据必须是可扩展的
  // 5. !value._isVue, 所有vue实例的_isVue属性都为true, 避免观测vue实例对象
  } else if (
    shouldObserve &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    ob = new Observer(value)
  }
  if (asRootData && ob) {
    ob.vmCount++
  }
  return ob
}

可以见得observe函数的作用是:检查对象上是否有ob属性,如果存在,则表明该对象已经处于Observer的观察中,如果不存在,则new Observer来观察对象。
回到上文,数组说完了,那么来说对象的函数walk调用,我们看到直接是调用了defineReactive函数,那我们来一探究竟:

// 定义响应式对象, 给对象动态添加get set拦截方法,
export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  const dep = new Dep()

  const property = Object.getOwnPropertyDescriptor(obj, key)
  if (property && property.configurable === false) {
    return
  }

  // cater for pre-defined getter/setters
  const getter = property && property.get
  if (!getter && arguments.length === 2) {
    val = obj[key]
  }
  const setter = property && property.set

  let childOb = !shallow && observe(val)
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      const value = getter ? getter.call(obj) : val
      if (Dep.target) {
        dep.depend()
        if (childOb) {
          childOb.dep.depend()
          if (Array.isArray(value)) {
            dependArray(value)
          }
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      const value = getter ? getter.call(obj) : val
      /* eslint-disable no-self-compare */
      // 判断NaN的情况
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      /* eslint-enable no-self-compare */
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter()
      }
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      childOb = !shallow && observe(newVal)
      dep.notify()
    }
  })
}

可以见得defineReactive函数的作用是:通过Object.defineProperty设置对象的key属性,使得能够捕获到该属性值的set/get操作,且observe函数深度遍历,所以把所有的属性都添加到了Observe上面了,也就是说,咱们对数据的读写就会触发getter/setter,再者我们可以看到get方法里面有Dep.target这个变量,dep.dependdependArrayset方法里面有dep.notify这些方法,可想而知,我们依赖了Dep这个文件:

参考 前端进阶面试题详细解答

export default class Dep {
  // target是一个全局唯一的Watcher
  static target: ?Watcher;
  id: number;
  subs: Array<Watcher>;
  // 生成每个实例唯一的uid, subs用于存储watcher
  constructor () {
    this.id = uid++
    this.subs = []
  }

  // 添加一个watcher
  addSub (sub: Watcher) {
    this.subs.push(sub)
  }

  // 删除一个watcher
  removeSub (sub: Watcher) {
    remove(this.subs, sub)
  }

  // 将自身加入到全局的watcher中
  depend () {
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

  // 通知所有订阅者
  notify () {
    // stabilize the subscriber list first
    const subs = this.subs.slice()
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}

观察dep文件,我们可以看到一个Dep类,其中有几个方法:

  • addSub: 接收的参数为Watcher实例,并把Watcher实例存入记录依赖的数组中
  • removeSub:addSub对应,作用是将Watcher实例从记录依赖的数组中移除
  • depend: Dep.target上存放这当前需要操作的Watcher实例,调用depend会调用该 Watcher实例的addDep方法。
  • notify: 通知依赖数组中所有的watcher进行更新操作
    而且创造了一个subs用来存储订阅者。
    分析完了之后,我们就总结出一句话,dep是一个用来存储所有订阅者watcher的对象,他的notify方法就是去遍历通知所有的Watcher订阅者数据源发生了改变需要去更新视图了。
    那么我们再来看一下Watcher的结构是咋样的:
export default class Watcher {
  vm: Component;
  expression: string;
  cb: Function;
  id: number;
  deep: boolean;
  user: boolean;
  lazy: boolean;
  sync: boolean;
  dirty: boolean;
  active: boolean;
  deps: Array<Dep>;
  newDeps: Array<Dep>;
  depIds: SimpleSet;
  newDepIds: SimpleSet;
  getter: Function;
  value: any;

  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    this.vm = vm
    if (isRenderWatcher) {
      vm._watcher = this
    }
    vm._watchers.push(this)
    // options
    if (options) {
      this.deep = !!options.deep
      this.user = !!options.user
      this.lazy = !!options.lazy
      this.sync = !!options.sync
    } else {
      this.deep = this.user = this.lazy = this.sync = false
    }
    this.cb = cb
    this.id = ++uid // uid for batching
    this.active = true
    this.dirty = this.lazy // for lazy watchers
    this.deps = []
    this.newDeps = []
    this.depIds = new Set()
    this.newDepIds = new Set()
    this.expression = process.env.NODE_ENV !== 'production'
      ? expOrFn.toString()
      : ''
    // parse expression for getter
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } else {
      this.getter = parsePath(expOrFn)
      if (!this.getter) {
        this.getter = function () {}
        process.env.NODE_ENV !== 'production' && warn(
          `Failed watching path: "${expOrFn}" ` +
          'Watcher only accepts simple dot-delimited paths. ' +
          'For full control, use a function instead.',
          vm
        )
      }
    }
    this.value = this.lazy
      ? undefined
      : this.get()
  }

  /**   * Evaluate the getter, and re-collect dependencies.   */
  get () {
    pushTarget(this)
    let value
    const vm = this.vm
    try {
      value = this.getter.call(vm, vm)
    } catch (e) {
      if (this.user) {
        handleError(e, vm, `getter for watcher "${this.expression}"`)
      } else {
        throw e
      }
    } finally {
      // "touch" every property so they are all tracked as
      // dependencies for deep watching
      if (this.deep) {
        traverse(value)
      }
      popTarget()
      this.cleanupDeps()
    }
    return value
  }

  /**   * 接收参数`dep(Dep实例)`,让当前`watcher`订阅`dep`   */
  addDep (dep: Dep) {
    const id = dep.id
    if (!this.newDepIds.has(id)) {
      this.newDepIds.add(id)
      this.newDeps.push(dep)
      if (!this.depIds.has(id)) {
        dep.addSub(this)
      }
    }
  }

  /**   * 清除`newDepIds和newDep`上记录的对dep的订阅信息   */
  cleanupDeps () {
    let i = this.deps.length
    while (i--) {
      const dep = this.deps[i]
      if (!this.newDepIds.has(dep.id)) {
        dep.removeSub(this)
      }
    }
    let tmp = this.depIds
    this.depIds = this.newDepIds
    this.newDepIds = tmp
    this.newDepIds.clear()
    tmp = this.deps
    this.deps = this.newDeps
    this.newDeps = tmp
    this.newDeps.length = 0
  }

  /**   * 立刻运行`watcher`或者将`watcher`加入队列中等待统一`flush`   */
  update () {
    /* istanbul ignore else */
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) {
      this.run()
    } else {
      queueWatcher(this)
    }
  }

  /**   * 运行`watcher`,调用`this.get()`求值,然后触发回调   */
  run () {
    if (this.active) {
      const value = this.get()
      if (
        value !== this.value ||
        // Deep watchers and watchers on Object/Arrays should fire even
        // when the value is the same, because the value may
        // have mutated.
        isObject(value) ||
        this.deep
      ) {
        // set new value
        const oldValue = this.value
        this.value = value
        if (this.user) {
          try {
            this.cb.call(this.vm, value, oldValue)
          } catch (e) {
            handleError(e, this.vm, `callback for watcher "${this.expression}"`)
          }
        } else {
          this.cb.call(this.vm, value, oldValue)
        }
      }
    }
  }

  /**   *调用`this.get()`求值   */
  evaluate () {
    this.value = this.get()
    this.dirty = false
  }

  /**   * 遍历`this.deps`,让当前`watcher`实例订阅所有`dep`   */
  depend () {
    let i = this.deps.length
    while (i--) {
      this.deps[i].depend()
    }
  }

  /**   *去除当前`watcher`实例所有的订阅   */
  teardown () {
    if (this.active) {
      // remove self from vm's watcher list
      // this is a somewhat expensive operation so we skip it
      // if the vm is being destroyed.
      if (!this.vm._isBeingDestroyed) {
        remove(this.vm._watchers, this)
      }
      let i = this.deps.length
      while (i--) {
        this.deps[i].removeSub(this)
      }
      this.active = false
    }
  }
}

我们看到了一个Watcher类,并且有一些方法:

  • get:Dep.target设置为当前watcher实例,在内部调用this.getter,如果此时某个被 Observer观察的数据对象被取值了,那么当前watcher实例将会自动订阅数据对象的Dep实例
  • addDep: 接收参数dep(Dep实例),让当前watcher订阅dep
  • cleanupDeps: 清除newDepIds和newDep上记录的对dep的订阅信息
  • update: 立刻运行watcher或者将watcher加入队列中等待统一fresh
  • run: 运行watcher,调用this.get()求值,然后触发回调
  • evaluate: 调用this.get()求值
  • depend: 遍历this.deps,让当前watcher实例订阅所有dep
  • teardown: 去除当前watcher实例所有的订阅
    那么我们知道这么多方法,来梳理一下流程
    在这里插入图片描述

我们的数据发生变化,我们data里面所有的属性都可以看做一个dep,而dep里面的subs就是存放当前属性的地方,当我们数据发生变化的时候就不会被监听到,我们就要通过dep去调用notify方法通知所有的Watcher进行更新视图。
那么问题又来了,这个this.subs是如何添加订阅者的?

get () {
    pushTarget(this)
    let value
    const vm = this.vm
    try {
      value = this.getter.call(vm, vm)
    } catch (e) {
      if (this.user) {
        handleError(e, vm, `getter for watcher "${this.expression}"`)
      } else {
        throw e
      }
    } finally {
      // "touch" every property so they are all tracked as
      // dependencies for deep watching
      if (this.deep) {
        traverse(value)
      }
      popTarget()
      this.cleanupDeps()
    }
    return value
  }

  /**   * Add a dependency to this directive.   */
  addDep (dep: Dep) {
    const id = dep.id
    if (!this.newDepIds.has(id)) {
      this.newDepIds.add(id)
      this.newDeps.push(dep)
      if (!this.depIds.has(id)) {
        dep.addSub(this)
      }
    }
  }

我们在Dep中可以看到Dep在一开始定义了一个全局属性Dep.target,在新建watcher是,这个属性为null,而在watcher的构造函数中最后会执行自己的get()方法,进而执行pushTarget(this)方法:

// 将watcher实例赋值给Dep.target,用于依赖收集。同时将该实例存入target栈中
export function pushTarget (_target: ?Watcher) {
  if (Dep.target) targetStack.push(Dep.target)
  Dep.target = _target
}

可以看到get()方法,value = this.getter.call(vm, vm),然后popTarget()方法:

// 从target栈取出一个watcher实例
export function popTarget () {
  Dep.target = targetStack.pop()
}

Dep.target只是一个标记,存储当前的watcher实例,触发Object.defineProperty中的get拦截,而在Oject.defineProperty中的get那里,我们可以看到dep.depend(),正是在这里将当前的订阅者watcher绑定当Dep上。
也就是说,每个watcher第一次实例化的时候,都会作为订阅者订阅其相应的Dep

写到这里,相信各位对数据响应式已经有很深刻的理解了吧,那么我们还有一个话题,我们是如何进行初始化渲染更新二次更新视图的?下章我们讨论一下。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/380914.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

LeetCode:构造最大二叉树;使用中序和后序数组构造二叉树;使用前序和中序数组遍历二叉树。

构造二叉树最好都是使用前序遍历&#xff1b;中左右的顺序。 654. 最大二叉树 中等 636 给定一个不重复的整数数组 nums 。 最大二叉树 可以用下面的算法从 nums 递归地构建: 创建一个根节点&#xff0c;其值为 nums 中的最大值。递归地在最大值 左边 的 子数组前缀上 构建…

人力资源管理系统

技术&#xff1a;Java、JSP等摘要&#xff1a;在当今的信息化社会&#xff0c;为了更有效率地工作&#xff0c;人们充分利用现在的电子信息技术&#xff0c;在办公室架设起办公服务平台&#xff0c;将人力资源相关信息统一起来管理&#xff0c;帮助管理者有效组织降低成本和加速…

【Linux】gcc/g++/gdb的使用

&#x1f525;&#x1f525; 欢迎来到小林的博客&#xff01;&#xff01;       &#x1f6f0;️博客主页&#xff1a;✈️小林爱敲代码       &#x1f6f0;️社区 : 进步学堂       &#x1f6f0;️欢迎关注&#xff1a;&#x1f44d;点赞&#x1f64c;收…

Mask R-CNN 算法学习总结

Mask R-CNN 相关知识点整体框架1.Resnet 深度残差学习1.1 目的1.2 深度学习深度增加带来的问题1.3 Resnet实现思想【添加恒等映射】2.线性插值2.1 目的2.2 线性插值原理2.3 为什么使用线性插值?3.FPN 特征金字塔3.1 FPN介绍3.2 为什么使用FPN?3.3 自下而上层【提取特征】3.4 …

反激与正激的区别

之前学习了正激开关电源&#xff0c;但是对于正激和反激一直不是很清楚&#xff0c;网上找了一篇&#xff0c;觉得感觉该可以&#xff0c;以此记录。正激和反激是两种不同的开关电源技术一、正激&#xff08;1&#xff09;概述正激式开关电源是指使用正激高频变压器隔离耦合能量…

深度学习笔记:神经网络权重确定初始值方法

神经网络权重不可为相同的值&#xff0c;比如都为0&#xff0c;因为如果这样网络正向传播输出和反向传播结果对于各权重都完全一样&#xff0c;导致设置多个权重和设一个权重毫无区别。我们需要使用随机数作为网络权重 实验程序 在以下实验中&#xff0c;我们使用5层神经网络…

设计模式-服务定位器模式

设计模式-服务定位器模式一、背景1.1 服务定位模式1.2 策略模式二、代码实战2.1 服务定位器2.2 配置ServiceLocatorFactoryBean2.3 定义一个支付的接口2.4 根据不同类型处理Bean2.5 controller层三、项目结构及测试结果3.1 测试结果3.2 项目结构及源码(欢迎star)四、参考资料一…

进程管理(进程概念、查看进程、关闭进程)

1.进程 程序运行在操作系统中&#xff0c;是被操作系统所管理的。 为管理运行的程序&#xff0c;每一个程序运行的时候&#xff0c;便被操作系统注册为系统中的一个&#xff1a;进程 并会为每一个进程都分配一个独有的&#xff1a;进程ID&#xff08;进程号&#xff09; 2. 查…

Paddle OCR Win 11下的安装和简单使用教程

Paddle OCR Win 11下的安装和简单使用教程 对于中文的识别&#xff0c;可以考虑直接使用Paddle OCR&#xff0c;识别准确率和部署都相对比较方便。 环境搭建 目前PaddlePaddle 发布到v2.4&#xff0c;先下载paddlepaddle&#xff0c;再下载paddleocr。根据自己设备操作系统进…

代码随想录算法训练营第四十天 | 343. 整数拆分,96.不同的二叉搜索树

一、参考资料整数拆分https://programmercarl.com/0343.%E6%95%B4%E6%95%B0%E6%8B%86%E5%88%86.html 视频讲解&#xff1a;https://www.bilibili.com/video/BV1Mg411q7YJ不同的二叉搜索树https://programmercarl.com/0096.%E4%B8%8D%E5%90%8C%E7%9A%84%E4%BA%8C%E5%8F%89%E6%90…

Win10任务栏卡死的几个处理方法 附小工具

问题&#xff1a;Win10任务栏卡死 最近经常碰到用户系统任务栏卡死的现象&#xff0c;桌面上的图标可以正常打开&#xff0c;点击任务栏就疯狂的转圈&#xff0c;感觉像死机状态&#xff0c;等半天都没啥用&#xff0c;一般只能强制关机重启&#xff0c;我不建议这样操作&…

机器学习算法原理——感知机

感知机 输入空间&#xff1a;X⊆Rn\mathcal X\subseteq{\bf R^n}X⊆Rn &#xff1b;输入&#xff1a;x(x(1),x(2),⋅⋅⋅,x(n))T∈Xx\left(x^{(1)},x^{(2)},\cdot\cdot\cdot,x^{(n)}\right)^{T}\in{\mathcal{X}}x(x(1),x(2),⋅⋅⋅,x(n))T∈X 输出空间&#xff1a;Y{1,−1}{\…

杂谈:created中两次数据修改,会触发几次页面更新?

面试题&#xff1a;created生命周期中两次修改数据&#xff0c;会触发几次页面更新&#xff1f; 一、同步的 先举个简单的同步的例子&#xff1a; new Vue({el: "#app",template: <div><div>{{count}}</div></div>,data() {return {count…

[架构之路-124]-《软考-系统架构设计师》-操作系统-3-操作系统原理 - IO设备、微内核、嵌入式系统

第11章 操作系统第5节 设备管理/文件管理&#xff1a;IO5.1 文件管理5.2 IO设备管理&#xff08;内存与IO设备之间&#xff09;数据传输控制是指如何在内存和IO硬件设备之间传输数据&#xff0c;即&#xff1a;设备何时空闲&#xff1f;设备何时完成数据的传输&#xff1f;SPOO…

vue实战-深入响应式数据原理

本文将带大家快速过一遍Vue数据响应式原理&#xff0c;解析源码&#xff0c;学习设计思路&#xff0c;循序渐进。 数据初始化 _init 在我们执行new Vue创建实例时&#xff0c;会调用如下构造函数&#xff0c;在该函数内部调用this._init(options)。 import { initMixin } f…

代码随想录算法训练营第一天| 704. 二分查找、27. 移除元素

Leetcode 704 二分查找题目链接&#xff1a;704二分查找介绍给定一个 n 个元素有序的&#xff08;升序&#xff09;整型数组 nums 和一个目标值 target &#xff0c;写一个函数搜索 nums 中的 target&#xff0c;如果目标值存在返回下标&#xff0c;否则返回 -1。思路先看看一个…

MyBatis源码分析(三)SqlSession的执行主流程

文章目录一、熟悉主要接口二、SqlSession的获取1、通过数据源获取SqlSession三、Mapper的获取与代理1、从SqlSession获取Mapper2、执行Mapper方法前准备逻辑3、SqlCommand的创建4、构造MethodSignature四、执行Mapper的核心方法1、执行Mapper的方法逻辑五、简单SELECT处理过程1…

【蓝桥杯试题】 递归实现指数型枚举例题

&#x1f483;&#x1f3fc; 本人简介&#xff1a;男 &#x1f476;&#x1f3fc; 年龄&#xff1a;18 &#x1f91e; 作者&#xff1a;那就叫我亮亮叭 &#x1f4d5; 专栏&#xff1a;蓝桥杯试题 文章目录1. 题目描述2. 思路解释2.1 时间复杂度2.2 递归3. 代码展示最后&#x…

超级简单又功能强大还免费的电路仿真软件

设计电路的时候经常需要进行一些电路仿真。常用的仿真软件很多&#xff0c;由于大学里经常使用Multisim作为教学软件&#xff0c;所以基本上所有从事硬件开发的人都听过或者用过Multisim这个软件。这个软件最大的好处就是简单直观&#xff0c;可以在自己的PC上搭建电路并使用软…

gdb常用命令详解

gdb常用调试命令概览和说明 run命令 在默认情况下&#xff0c;gdbfilename只是attach到一个调试文件&#xff0c;并没有启动这个程序&#xff0c;我们需要输入run命令启动这个程序&#xff08;run命令被简写成r&#xff09;。如果程序已经启动&#xff0c;则再次输入 run 命令…