资讯专栏INFORMATION COLUMN

vue:响应原理

cyrils / 3265人阅读

摘要:通知某属性改变,遍历所有的订阅者,就是实例,然后调用实例的方法些方法最核心的部分就是通过调用给的每个属性添加和方法。

vue生命周期图示:

Vue.js最显著的功能就是响应式系统,它是一个典型的MVVM框架,Model只是普通的Javascript对象,修改它则View会自动更新,这种设计让状态管理变得非常简单而直观。

如何追踪变化?我们先看一个简单的例子:

count:{{times}}

运行后,我们可以从页面中看到,count后面的times每隔一秒递增1,视图一直在更新,在代码中仅仅是通过setInterval方法每隔一秒来修改vm.times的值,并没有任何dom操作,那么vue是怎么实现这个过程呢,我们通过一张图来看下:

图中的Model就是data方法返回的{times:1},View是最终在浏览器中显示的DOM,模型通过Observer,Dep,Watcher,Directive等一系列对象的关联,最终和视图建立起关系。总的来说,vue在些做了3件事:

通过Observerdata做监听,并提供了订阅某个数据项变化的能力。

template编译成一段document fragment,然后解析其中的Directive,得到每一个Directive所依赖的数据项和update方法。

通过Watcher把上述2部分结合起来,即把Directive中的数据依赖通过Watcher订阅在对应数据的ObserverDep上,当数据变化时,就会触发ObserverDep上的notify方法通知对应的Watcherupdate,进而触发Directiveupdate方法来更新dom视图,最后达到模型和视图关联起来。

Observer

我们来看下vue是如何给data对象添加Observer的,我们知道,vue的实例创建的过程会有一个生命周期,其中有一个过程就是调用vm.initData方法处理data选项,代码如下:

src/core/instance/state.js

function initData (vm: Component) {
  let data = vm.$options.data
  data = vm._data = typeof data === "function" ? getData(data, vm) : data || {}
  if (!isPlainObject(data)) {
    data = {}
    process.env.NODE_ENV !== "production" && warn(
      "data functions should return an object:
" +
      "https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function",
      vm
    )
  }
  // proxy data on instance
  const keys = Object.keys(data)
  const props = vm.$options.props
  const methods = vm.$options.methods
  let i = keys.length
  while (i--) {
    const key = keys[i]
    if (process.env.NODE_ENV !== "production") {
      if (methods && hasOwn(methods, key)) {
        warn(
          `Method "${key}" has already been defined as a data property.`,
          vm
        )
      }
    }
    if (props && hasOwn(props, key)) {
      process.env.NODE_ENV !== "production" && warn(
        `The data property "${key}" is already declared as a prop. ` +
        `Use prop default value instead.`,
        vm
      )
    } else if (!isReserved(key)) {
      proxy(vm, `_data`, key)
    }
  }
  // observe data
  observe(data, true /* asRootData */)
}

我们要注意下proxy方法,它的功能是遍历datakey,把data上的属性代理到vm实例上,proxy源码如下:

const sharedPropertyDefinition = {
  enumerable: true,
  configurable: true,
  get: noop,
  set: noop
}

function proxy (target: Object, sourceKey: string, key: string) {
  sharedPropertyDefinition.get = function proxyGetter () {
    return this[sourceKey][key]
  }
  sharedPropertyDefinition.set = function proxySetter (val) {
    this[sourceKey][key] = val
  }
  Object.defineProperty(target, key, sharedPropertyDefinition)
}

方法主要通过Object.definePropertygettersetter方法实现了代理,在 前面的例子中,我们调用vm.times就相当于访问了vm._data.times.

initData的最后,我们调用了observer(data,this)来对data做监听,observer的源码定义如下:

src/core/observer/index.js

/**
 *尝试创建一个值的观察者实例,
 *如果成功观察到新的观察者,
 *或现有的观察者,如果该值已经有一个。
 */
export function observe (value: any, asRootData: ?boolean): Observer | void {
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  let ob: Observer | void
  if (hasOwn(value, "__ob__") && value.__ob__ instanceof Observer) {
    ob = value.__ob__
  } else if (
    observerState.shouldConvert &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    ob = new Observer(value)
  }
  if (asRootData && ob) {
    ob.vmCount++
  }
  return ob
}

它会首先判断value是否已经添加了_ob_属性,它是一个Observer对象的实例,如果是就直接用,否则在value满足一些条件(数组或对象,可扩展,非vue组件等)的情况下创建一个Observer对象,下面看下Observer这个类的源码:

class Observer {
  value: any;
  dep: Dep;
  vmCount: number; // 将这个对象作为根$data的vm的数量。

  constructor (value: any) {
    this.value = value
    this.dep = new Dep()
    this.vmCount = 0
    def(value, "__ob__", this)
    if (Array.isArray(value)) {
      const augment = hasProto
        ? protoAugment
        : copyAugment
      augment(value, arrayMethods, arrayKeys)
      this.observeArray(value)
    } else {
      this.walk(value)
    }
  }

  /**
   *遍历每个属性并将其转换为拥有getter / setter。这个方法应该只在什么时候调用。当obj是对象。
   */
  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i], obj[keys[i]])
    }
  }

  /**
   观察数组项的列表。
   */
  observeArray (items: Array) {
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}

这个构造函数主要做了这么几件事,首先创建了一个Dep对象实例,然后把自身this添加到value_ob_属性上,最后对value的类型进行判断,如果是数组则观察数组,否则观察单个元素。obsersverArray方法就是对数组进行遍历,递归调用observer方法,最终都会调用walk方法观察单个元素。walk方法就是对objkey进行遍历。然后调用了defineReactive,把要观察的data对象的每个属性都赋予gettersetter方法,这样一旦属性被访问或者更新,我们就可以追踪到这些变化。源码如下:

/**
 * 在对象上定义一个反应性属性 setter,getter。
 */
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
  }

  // 满足预定义的getter / setter
  const getter = property && property.get
  const setter = property && property.set

  let childOb = !shallow && observe(val)
    // 在这里添加setter,getter。
  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 */
      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)
        // 通知data某属性改变,遍历所有的订阅者,就是watcher实例,然后调用watcher实例的update方法
      dep.notify()
    }
  })
}

些方法最核心的部分就是通过调用Object.definePropertydata的每个属性添加gettersetter方法。当data的某个属性被访问时,则会调用getter方法,判断当Dep.target不为空时调用dep.dependchildOb.dep.depend方法做依赖收集,如果访问的属性是一个数组则会遍历这个数组收集数组元素的依赖,当改变data的属性时,则会调用setter方法,这时调用dep.notify方法进行通知。其中用到的Dep类是一个简单的观察者模式的实现,然后我们看下源码:

src/core/observer/dep.js

class Dep {
  static target: ?Watcher;
  id: number;
  subs: Array;

  constructor () {
    this.id = uid++
    this.subs = [] // 用来存储所有订阅它的watcher
  }

  addSub (sub: Watcher) {
    this.subs.push(sub)
  }

  removeSub (sub: Watcher) {
    remove(this.subs, sub)
  }

  depend () {
    if (Dep.target) { // Dep.target表示当前正在计算的watcher,是全局唯一的,同一时间只能有一个watcher被计算
      // 把当前Dep的实例添加到当前正在计算的watcher依赖中
      Dep.target.addDep(this)
    }
  }
// 遍历所有的的订阅watcher,调用它们的update方法。
  notify () {
    // 首先稳定用户列表。
    const subs = this.subs.slice()
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}
watcher
src/core/observer/watcher.js

let uid = 0

/**
 * 观察者解析表达式,收集依赖项,
 *当表达式值发生变化时触发回调。
 这用于$watch() api和指令。
 */
export default class Watcher {
 
  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: Object
  ) {
    this.vm = vm
    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 为批处理
    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()
  }

  /**
   * 评估getter并重新收集依赖项。
   */
  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 {
      // “触摸”每个属性,所以它们都被跟踪。
        // 对深度观察的依赖。
      if (this.deep) {
        traverse(value)
      }
      popTarget()
      this.cleanupDeps()
    }
    return value
  }

  /**
   * Add a dependency to this directive.把dep添加到watcher实例的依赖中,同时通过            dep.addsup(this)把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)
      }
    }
  }

  /**
   * Clean up for dependency collection.
   */
  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
  }

  /**
   *用户界面。时将调用一个依赖的变化。
   */
  update () {
    /* istanbul ignore else */
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) {
      this.run()
    } else { // 调用,把watcher实例推入队列中,延迟this.run调用的时机。
      queueWatcher(this)
    }
  }

  /**
   * 调度器的工作界面。会被调度器调用。
   * 再次对watcher进行求值,重新收集依赖,接下来判断求值结果和之前value的关系,如果不变,则什么也不做
   * 此方法是directive实例创建watcher时传入的,它对应相关指令的update方法来真实更新dom。这样就完成了数据更新到对应视图的变化过程。
   * watcher把observer和directive关联起来,实现了数据一旦更新,视图就自动变化的效果。利用object.defineProperty实现了数据和视图的绑定
   */
  run () {
    if (this.active) {
      const value = this.get()
      if (
        value !== this.value ||
        // 深入观察和观察对象/阵列甚至应该开火。当值相等时,因为值可以。有突变。
        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)
        }
      }
    }
  }

  /**
   * 评估观察者的价值。
   这只会被称为懒惰的观察者。
   */
  evaluate () {
    this.value = this.get() // 对watcher进行求值,同时收集依赖
    this.dirty = false // 不会再对watcher求值,也不会再访问计算属性的getter方法了
  }

  /**
   * 要看这个观察者收集的所有数据。
   */
  depend () {
    let i = this.deps.length
    while (i--) {
      this.deps[i].depend()
    }
  }

  /**
   * Remove self from all dependencies" subscriber list.
   */
  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
    }
  }
}

Dep实例在初始化watcher时,会传入指令的expression.在前面的例子中expressiontimes.get方法的功能是对当前watcher进行求值,收集依赖关系,设置Dep.target为当前watcher的实例,this.getter.call(vm,vm),这个方法相当于获取vm.times,这样就触发了对象的getter.我们之前给data添加Observer时,通过上面defineReactive/Object.definePropertydata对象的每一个属性添加gettersetter了.

src/core/observer/index.js

function defineReactive (obj,key,val,customSetter,shallow) {
  // 在这里添加setter,getter。
  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
    }
 }

当获取vm.times时,会执行到get方法体内,由于我们在之前已经设置了Dep.target为当前Watcher实例,所以接下来就调用dep.depend()完成收集,它实际上是执行了Dep.target.addDep(this),相当于执行了Watcher实例的addDep方法,把Dep添加到Watcher实例的依赖中。

src/observer/watcher.js

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)
      }
    }
  }

addDep是把dep添加到Watcher实例的依赖中,同时又通过dep.addSup(this)Watcher实例添加到dep的订阅者中

src/observer/dep.js

addSub (sub: Watcher) {
    this.subs.push(sub)
  }

至此,指令完成了依赖收集,并且通过Watcher完成了对数据变化的订阅。

我们再看下,当data发生变化时,视图是如何自动更新的,在前面的例子中,我们setInterval每隔一秒执行一次vm.times++,数据改变会触发对象的setter,执行set方法体的代码。

src/core/observer/index.js

function defineReactive (obj,key,val,customSetter,shallow) {
  // 在这里添加setter,getter。
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    set: function reactiveSetter (newVal) {
      const value = getter ? getter.call(obj) : val
    
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      
      if (process.env.NODE_ENV !== "production" && customSetter) {
        customSetter()
      }
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      childOb = !shallow && observe(newVal)
      // 通知data某属性改变,遍历所有的订阅者,就是watcher实例,然后调用watcher实例的update方法
      dep.notify()
    }
 }
src/observer/watcher.js

update () {
    /* istanbul ignore else */
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) {
      this.run()
    } else { 
      queueWatcher(this)// 调用,把watcher实例推入队列中,延迟this.run调用的时机。
    }
  }
src/core/observer/scheduler.js

/**
 * 把一个观察者watcher推入观察者队列。
 *将跳过具有重复id的作业,除非它是。
 *当队列被刷新时被推。
 * 通过nextTick在下一个事件循环周期处理watcher队列,是一种优化手段。因为如果同时观察的数据多次变化,比如同步执行3次vm.time++,同时调用就会触发3次dom操作
 * 而推入队列中等待下一个事件循环周期再操作队列里的watcher,因为是同一个watcher,它只会调用一次watcher.run,从而只触发一次dom操作。
 */
export function queueWatcher (watcher: Watcher) {
  const id = watcher.id
  if (has[id] == null) {
    has[id] = true
    if (!flushing) {
      queue.push(watcher)
    } else {
      // 如果已经刷新,则根据其id将监视器拼接起来。
        // 如果已经超过了它的id,它将会立即运行。
      let i = queue.length - 1
      while (i > index && queue[i].id > watcher.id) {
        i--
      }
      queue.splice(i + 1, 0, watcher)
    }
    // 队列的冲
    if (!waiting) {
      waiting = true
      nextTick(flushSchedulerQueue)
    }
  }
}
function flushSchedulerQueue () {
  flushing = true
  let watcher, id

    // 在刷新前排序队列。
    // 这确保:
    // 1。组件由父元素更新为子元素。(因为父母总是在孩子面前创建)
    // 2。组件的用户观察者在它的呈现观察者之前运行(因为用户观察者是在渲染观察者之前创建的
    // 3。如果组件在父组件的监视程序运行期间被销毁, 它的观察者可以跳过。
  queue.sort((a, b) => a.id - b.id)

    // 不要缓存长度,因为可能会有更多的观察者被推。
    // 当我们运行现有的观察者时。遍历queue中watcher的run方法
  for (index = 0; index < queue.length; index++) {
    watcher = queue[index]
    id = watcher.id
    has[id] = null
    watcher.run()
    // in dev build, check and stop circular updates.
    if (process.env.NODE_ENV !== "production" && has[id] != null) {
      circular[id] = (circular[id] || 0) + 1
      if (circular[id] > MAX_UPDATE_COUNT) {
        warn(
          "You may have an infinite update loop " + (
            watcher.user
              ? `in watcher with expression "${watcher.expression}"`
              : `in a component render function.`
          ),
          watcher.vm
        )
        break
      }
    }
  }

  // keep copies of post queues before resetting state
  const activatedQueue = activatedChildren.slice()
  const updatedQueue = queue.slice()

  resetSchedulerState()

  // call component updated and activated hooks
  callActivatedHooks(activatedQueue)
  callUpdatedHooks(updatedQueue)

  // devtool hook
  /* istanbul ignore if */
  if (devtools && config.devtools) {
    devtools.emit("flush")
  }
}

遍历queueWatcherrun方法,

src/core/observer/watcher.js

run () {
    if (this.active) {
      const value = this.get()
      if (
        value !== this.value ||
        // 深入观察和观察对象/阵列甚至应该开火。当值相等时,因为值可以。有突变。
        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)
        }
      }
    }
  }

run方法再次对Watcher求值,重新收集依赖,接下来判断求值结果和之前value的关系,如果不变则什么也不做,如果变了则调用this.cb.call(this.vm,value,oldValue)方法,这个方法是Directive实例创建watcher时传入的,它对应相关指令的update方法来真实更新 DOM,这样就完成了数据更新到对应视图的变化过程。Watcher巧妙的把ObserverDirective关联起来,实现了数据一旦更新,视图就会自动变化的效果,vue利用了Object.defineProperty这个核心技术实现了数据和视图的绑定。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/93030.html

相关文章

  • vue - 响应原理梳理(一)

    摘要:问题为什么修改即可触发更新和的关联关系官方介绍的官网文档,对响应式属性的原理有一个介绍。因此本文在源码层面,对响应式原理进行梳理,对关键步骤进行解析。 描述  我们通过一个简单的 Vue应用 来演示 Vue的响应式属性: html: {{message}} js: let vm = new Vue({ el: #ap...

    weknow619 评论0 收藏0
  • Vue原理响应原理 - 白话版

    摘要:所以我今后打算把每一个内容分成白话版和源码版。有什么错误的地方,感谢大家能够指出响应式系统我们都知道,只要在实例中声明过的数据,那么这个数据就是响应式的。什么是响应式,也即是说,数据发生改变的时候,视图会重新渲染,匹配更新为最新的值。 写文章不容易,点个赞呗兄弟专注 Vue 源码分享,文章分为白话版和 源码版,白话版助于理解工作原理,源码版助于了解内部详情,让我们一起学习吧研究基于 V...

    gggggggbong 评论0 收藏0
  • 浅究Vue响应原理

    摘要:在读取访问器属性时,就会调用函数,该函数负责返回有效的值在写入访问器属性时,会调用函数并传入新值,该函数负责决定如何处理数据,但是这两个函数不一定非要同时存在。 前言 Vue最明显的特性之一便是它的响应式系统,其数据模型即是普通的 JavaScript 对象。而当你读取或写入它们时,视图便会进行响应操作。文章简要阐述下其实现原理,如有错误,还请不吝指正。个人博客链接:hiybm.cn ...

    Karuru 评论0 收藏0
  • Vue原理】Props - 源码版

    写文章不容易,点个赞呗兄弟专注 Vue 源码分享,文章分为白话版和 源码版,白话版助于理解工作原理,源码版助于了解内部详情,让我们一起学习吧研究基于 Vue版本 【2.5.17】 如果你觉得排版难看,请点击 下面链接 或者 拉到 下面关注公众号也可以吧 【Vue原理】Props - 源码版 今天记录 Props 源码流程,哎,这东西,就算是研究过了,也真是会随着时间慢慢忘记的。 幸好我做...

    light 评论0 收藏0
  • Vue 响应式实现原理(个人在学习完Vue基础的情况下的理解)

    摘要:对象用户看到的对象用户看到的是这个对象即是实际使用的对象实际使用的对象复制更新相应的代码实现对象代理响应式原理前提官网说过,限于现代浏览器限制,无法监测通过这种方式添加的属性,所以,他的响应式是建立在实例化对象的时候,预定义属性的基础上的。 1. Vue 对象 1.1 用户看到的对象 var app = new Vue({ el: #app , /* * 用...

    zsy888 评论0 收藏0
  • vue - 响应原理梳理(二)

    摘要:原型方法通过原型方法方法来挂载实例。当响应式属性发生变化时,会通知依赖列表中的对象进行更新。此时,对象执行方法,重新渲染节点。在执行过程中,如果需要读取响应式属性,则会触发响应式属性的。总结响应式属性的原理 vue实例 初始化 完成以后,接下来就要进行 挂载。 vue实例挂载,即为将vue实例对应的 template模板,渲染成 Dom节点。 原型方法 - $mount   通过原...

    mochixuan 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<