vueソース解読(三、応答式原理)

15737 ワード

概要
Vueのデータ駆動は、データレンダリングDOMのほかに、データの変更がDOMの変化をトリガすることが重要である.簡単な例を考えてみましょう.
{{ message }}
var app = new Vue({ el: '#app', data: { message: 'Hello Vue!' }, methods: { changeMsg() { this.message = 'Hello World!' } } })

メッセージの変更をクリックすると、データはどのように新しいデータにレンダリングされますか?
レスポンスオブジェクト
Vue.js実現応答式の核心はES 5を利用したObjectである.defineProperty,Object.definePropertyメソッドでは、オブジェクトに直接新しいプロパティを定義したり、オブジェクトの既存のプロパティを変更したりして、このオブジェクトに戻ります.コアはdescriptorで、ドキュメントを参照することができます.ここで最も関心を持っているのはgetとsetであり、getは属性に提供されるgetterメソッドであり、この属性にアクセスするとgetterメソッドがトリガーされます.setは属性に提供されるsetterメソッドであり、その属性を変更するとsetterメソッドがトリガーされます.オブジェクトがgetterとsetterを持つと、このオブジェクトを簡単にレスポンスオブジェクトと呼ぶことができます.
Vueの初期化フェーズで、Initメソッドが実行されると、initState(vm)メソッドが実行され、
export function initState (vm: Component) {
  vm._watchers = []
  const opts = vm.$options
  if (opts.props) initProps(vm, opts.props)
  if (opts.methods) initMethods(vm, opts.methods)
  if (opts.data) {
    initData(vm)
  } else {
    observe(vm._data = {}, true /* asRootData */)
  }
  if (opts.computed) initComputed(vm, opts.computed)
  if (opts.watch && opts.watch !== nativeWatch) {
    initWatch(vm, opts.watch)
  }
}

具体的にはinitData(vm)
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 */) }

dataの初期化の主なプロセスも2つのことをします.1つは、data関数を定義してオブジェクトを返す遍歴で、proxyを通じて各値vm.data.xxxはvmに代理します.xxx上;もう1つはobserveメソッドを呼び出してdata全体の変化を観測し、dataも応答式にし、vm.data.xxxは定義data戻り関数の対応する属性にアクセスし、
proxy
エージェントの役割はpropsとdata上の属性をvmインスタンスにエージェントすることである.
const sharedPropertyDefinition = {
  enumerable: true,
  configurable: true,
  get: noop,
  set: noop
}

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

observe
observeの機能はデータの変化を監視することです
/**
 * Attempt to create an observer instance for a value,
 * returns the new observer if successfully observed,
 * or the existing observer if the value already has one.
 */
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 (
    shouldObserve &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    ob = new Observer(value)
  }
  if (asRootData && ob) {
    ob.vmCount++
  }
  return ob
}

defineReactive
defineReactiveの機能は、応答型オブジェクトを定義し、オブジェクトにgetterとsetterを動的に追加することです.
/**
 * Define a reactive property on an Object.
 */
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
  const setter = property && property.set
  if ((!getter || setter) && arguments.length === 2) {
    val = obj[key]
  }

  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 */
      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関数は、Depオブジェクトのインスタンスを最初に初期化し、objのプロパティ記述子を取得し、サブオブジェクトに対してobserveメソッドを再帰的に呼び出します.これにより、objの構造がどんなに複雑であっても、そのすべてのサブプロパティが応答的なオブジェクトになることを保証します.これにより、objのネストされた深いプロパティにアクセスまたは変更できます.getterやsetterもトリガーできます.最後にObjectを利用する.definePropertyはobjのプロパティkeyにgetterとsetterを追加します.getterと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
  }

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

  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
    },
    // ...
  })
}

このコードは、const dep=new Dep()が1つのDepのインスタンスをインスタンス化し、get関数でdep.dependによって依存収集を行う2つの場所に注目する必要があります.
Dep
import type Watcher from './watcher'
import { remove } from '../util/index'

let uid = 0

/**
 * A dep is an observable that can have multiple
 * directives subscribing to it.
 */
export default class Dep {
  static target: ?Watcher;
  id: number;
  subs: Array;

  constructor () {
    this.id = uid++
    this.subs = []
  }

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

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

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

// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null
const targetStack = []

export function pushTarget (_target: ?Watcher) {
  if (Dep.target) targetStack.push(Dep.target)
  Dep.target = _target
}

export function popTarget () {
  Dep.target = targetStack.pop()
}

DepはClassで、いくつかの属性と方法を定義しています.ここで特に注意しなければならないのは、静的属性targetがあります.これはグローバルで唯一のWatcherです.これは非常に巧みな設計です.同じ時間にグローバルなWatcherが計算されるしかないためです.また、自身の属性subsもWatcherの配列です.Depは実際にはWatcherの管理であり、DepがWatcherから単独で存在することは意味がない.
Watcher
Watcher
let uid = 0

/**
 * A watcher parses an expression, collects dependencies,
 * and fires callback when the expression value changes.
 * This is used for both the $watch() api and directives.
 */
export default class Watcher {
  vm: Component;
  expression: string;
  cb: Function;
  id: number;
  deep: boolean;
  user: boolean;
  computed: boolean;
  sync: boolean;
  dirty: boolean;
  active: boolean;
  dep: Dep;
  deps: Array;
  newDeps: Array;
  depIds: SimpleSet;
  newDepIds: SimpleSet;
  before: ?Function;
  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.computed = !!options.computed
      this.sync = !!options.sync
      this.before = options.before
    } else {
      this.deep = this.user = this.computed = this.sync = false
    }
    this.cb = cb
    this.id = ++uid // uid for batching
    this.active = true
    this.dirty = this.computed // for computed 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
        )
      }
    }
    if (this.computed) {
      this.value = undefined
      this.dep = new Dep()
    } else {
      this.value = 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
  }

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

  /**
   * 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
  }
  // ...
}

依存収集プロセス
VueのmountプロセスはmountComponent関数によって行われ、その中には比較的重要な論理があり、大体以下の通りである.
updateComponent = () => {
  vm._update(vm._render(), hydrating)
}
new Watcher(vm, updateComponent, noop, {
  before () {
    if (vm._isMounted) {
      callHook(vm, 'beforeUpdate')
    }
  }
}, true /* isRenderWatcher */)

レンダリングwatcherをインスタンス化すると、まずwatcherの構造関数論理に入り、thisを実行します.get()メソッドは、get関数に入り、まずpushTarget(this)を実行します.
export function pushTarget (_target: Watcher) {
  if (Dep.target) targetStack.push(Dep.target)
  Dep.target = _target
}

実際には、現在のレンダリングwatcherにDep.targetを割り当ててスタックを圧縮します(リカバリ用).次に、
value = this.getter.call(vm, vm)

this.getter対応はupdateComponent関数であり、これは実際には実行されます.
vm._update(vm._render(), hydrating)

vm._が先に実行されます.render()メソッドは、このメソッドを解析するとレンダリングVNodeが生成され、このプロセスでvm上のデータにアクセスするため、データオブジェクトのgetterがトリガーされます.各オブジェクト値のgetterにはdepがあり、getterがトリガーされたときにdep.depend()メソッドが呼び出され、Dep.target.addDep(this)。が実行されます.さっき、dep.targetがwatcherをレンダリングするために割り当てられていたことについて説明しました.では、addDepメソッドに実行します.
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.addSub(this)を実行すると、thisが実行される.subs.push(sub)は,現在のwatcherをこのデータが持つdepのsubsに購読し,後続のデータが変化したときにどのsubsに通知できるかを準備することを目的とする.だからvm.render()プロセスでは、すべてのデータのgetterがトリガーされ、実際に収集に依存するプロセスが完了します.
更新の配布
収集依存の目的は,これらの応答型データが変化を送信し,それらのsetterをトリガするときに,どのサブスクライバに対応する論理処理を行うべきかを知るためであり,このプロセスを配布更新と呼ぶ.コンポーネントで応答するデータを変更するとsetterの論理がトリガーされ、dep.notify()メソッドが呼び出されます.
class Dep {
  // ...
  notify () {
  // stabilize the subscriber list first
    const subs = this.subs.slice()
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}

ここでの論理は非常に簡単で,すべてのsubs,すなわちWatcherのインスタンス配列を遍歴し,各watcherのupdateメソッドを呼び出す.
class Watcher {
  // ...
  update () {
    /* istanbul ignore else */
    if (this.computed) {
      // A computed property watcher has two modes: lazy and activated.
      // It initializes as lazy by default, and only becomes activated when
      // it is depended on by at least one subscriber, which is typically
      // another computed property or a component's render function.
      if (this.dep.subs.length === 0) {
        // In lazy mode, we don't want to perform computations until necessary,
        // so we simply mark the watcher as dirty. The actual computation is
        // performed just-in-time in this.evaluate() when the computed property
        // is accessed.
        this.dirty = true
      } else {
        // In activated mode, we want to proactively perform the computation
        // but only notify our subscribers when the value has indeed changed.
        this.getAndInvoke(() => {
          this.dep.notify()
        })
      }
    } else if (this.sync) {
      this.run()
    } else {
      queueWatcher(this)
    }
  }
}  

watcherをレンダリングする場合、これはthisを実行する.get()メソッドの評価時にgetterメソッドが実行されます.
updateComponent = () => {
  vm._update(vm._render(), hydrating)
}

これは、コンポーネントに関連するレスポンスデータを変更すると、コンポーネントの再レンダリングがトリガーされ、patchのプロセスが再実行されるためです.
まとめ
応答型コンポーネントのプロセスは、各コンポーネント内のdata,props,computedを応答型オブジェクトに変換し、setterとgetterメソッドを追加し、データに依存して収集し、最後に配布更新を実現し、新しい値に基づいて新しいレンダリングコンポーネントに達する.