vue:相应道理

vue生命周期图示:
《vue:相应道理》

Vue.js最明显的功用就是相应式体系,它是一个典范的MVVM框架,Model只是一般的Javascript对象,修正它则View会自动更新,这类设想让状况治理变得异常简朴而直观。

怎样追踪变化?我们先看一个简朴的例子:

<div id="main">
    <h1>count:{{times}}</h1>
</div>
<script src="vue.js"></script>
<script>
    const vm=new Vue({
        el:'main',
        data(){
            return {
                times:1
            }
        },
        created(){
            let me=this;
            setInterval(()=>{
                me.times++;
            },1000)
        }
    })
</script>

运转后,我们能够从页面中看到,count背面的times每隔一秒递增1,视图一直在更新,在代码中仅仅是经由历程setInterval要领每隔一秒来修正vm.times的值,并没有任何dom操纵,那末vue是怎样完成这个历程呢,我们经由历程一张图来看下:

《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:\n' +
      '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<any>) {
    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<Watcher>;

  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这个中心技术完成了数据和视图的绑定。

    原文作者:Waxiangyu
    原文地址: https://segmentfault.com/a/1190000013444088
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞