Vue源碼探究-數(shù)據(jù)綁定的實(shí)現(xiàn)

Vue源碼探究-數(shù)據(jù)綁定的實(shí)現(xiàn)

本篇代碼位于vue/src/core/observer/

在總結(jié)完數(shù)據(jù)綁定實(shí)現(xiàn)的邏輯架構(gòu)一篇后,已經(jīng)對Vue的數(shù)據(jù)觀察系統(tǒng)的角色和各自的功能有了比較透徹的了解,這一篇繼續(xù)仔細(xì)分析下源碼的具體實(shí)現(xiàn)。

Observer

// Observer類用來附加到每個觀察對象上。
// 將被觀察目標(biāo)對象的屬性鍵名轉(zhuǎn)換成存取器,
// 以此收集依賴和派發(fā)更新
/**
 * Observer class that is attached to each observed
 * object. Once attached, the observer converts the target
 * object's property keys into getter/setters that
 * collect dependencies and dispatch updates.
 */
 // 定義并導(dǎo)出 Observer 類
export class Observer {
  // 初始化觀測對象,依賴對象,實(shí)例計(jì)數(shù)器三個實(shí)例屬性
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that has this object as root $data

  // 構(gòu)造函數(shù)接受被觀測對象參數(shù)
  constructor (value: any) {
    // 將傳入的觀測對象賦予實(shí)例的value屬性
    this.value = value
    // 創(chuàng)建新的Dep依賴對象實(shí)例賦予dep屬性
    this.dep = new Dep()
    // 初始化實(shí)例的vmCount為0
    this.vmCount = 0
    // 將實(shí)例掛載到觀測對象的'__ob__‘屬性上
    def(value, '__ob__', this)
    // 如果觀測對象是數(shù)組
    if (Array.isArray(value)) {
      // 判斷是否可以使用__proto__屬性,以此甚至augment含糊
      const augment = hasProto
        ? protoAugment
        : copyAugment
      // 攔截原型對象并重新添加數(shù)組原型方法
      // 這里應(yīng)該是為了修復(fù)包裝存取器破壞了數(shù)組對象的原型繼承方法的問題
      augment(value, arrayMethods, arrayKeys)
      // 觀察數(shù)組中的對象
      this.observeArray(value)
    } else {
      // 遍歷每一個對象屬性轉(zhuǎn)換成包裝后的存取器
      this.walk(value)
    }
  }

  // walk方法用來遍歷對象的每一個屬性,并轉(zhuǎn)化成存取器
  // 只在觀測值是對象的情況下調(diào)用
  /**
   * Walk through each property and convert them into
   * getter/setters. This method should only be called when
   * value type is Object.
   */
  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      // 將每一個對象屬性轉(zhuǎn)換成存取器
      defineReactive(obj, keys[i])
    }
  }

  // 觀察數(shù)組對象
  /**
   * Observe a list of Array items.
   */
  observeArray (items: Array<any>) {
    // 遍歷每一個數(shù)組對象,并繼續(xù)觀察
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}

// 下面是兩個輔助函數(shù),用來根據(jù)是否可以使用對象的 __proto__屬性來攔截原型
// 函數(shù)比較簡單,不詳細(xì)解釋了
// helpers

/**
 * Augment an target Object or Array by intercepting
 * the prototype chain using __proto__
 */
function protoAugment (target, src: Object, keys: any) {
  /* eslint-disable no-proto */
  target.__proto__ = src
  /* eslint-enable no-proto */
}

/**
 * Augment an target Object or Array by defining
 * hidden properties.
 */
/* istanbul ignore next */
function copyAugment (target: Object, src: Object, keys: Array<string>) {
  for (let i = 0, l = keys.length; i < l; i++) {
    const key = keys[i]
    def(target, key, src[key])
  }
}

// observe函數(shù)用來為觀測值創(chuàng)建觀察目標(biāo)實(shí)例
// 如果成功被觀察則返回觀察目標(biāo),或返回已存在觀察目標(biāo)
/**
 * 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.
 */
 // 定義并導(dǎo)出observe函數(shù),接受觀測值和是否作為data的根屬性兩個參數(shù)
 // 返回Observer類型對象或空值
export function observe (value: any, asRootData: ?boolean): Observer | void {
  // 判斷是否為所要求的對象,否則不繼續(xù)執(zhí)行
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  // 定義Observer類型或空值的ob變量
  let ob: Observer | void
  // 如果觀測值具有__ob__屬性,并且其值是Observer實(shí)例,將其賦予ob
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    ob = value.__ob__
  } else if (
    // 如果shouldObserve為真,且不是服務(wù)器渲染,觀測值是數(shù)組或者對象
    // 觀測值可擴(kuò)展,且觀測值不是Vue實(shí)例,則創(chuàng)建新的觀察目標(biāo)實(shí)例賦予ob
    // 這里發(fā)現(xiàn)了在Vue核心類創(chuàng)建實(shí)例的時候設(shè)置的_isVue的用途了
    shouldObserve &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    ob = new Observer(value)
  }
  // 如果asRootData為真且ob對象存在,ob.vmCount自增
  if (asRootData && ob) {
    ob.vmCount++
  }
  // 返回ob
  return ob
}

// defineReactive函數(shù)用來為觀測值包賺存取器
/**
 * Define a reactive property on an Object.
 */
// 定義并導(dǎo)出defineReactive函數(shù),接受參數(shù)觀測源obj,屬性key, 值val,
// 自定義setter方法customSetter,是否進(jìn)行遞歸轉(zhuǎn)換shallow五個參數(shù)
export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  // 創(chuàng)建依賴對象實(shí)例
  const dep = new Dep()

  // 獲取obj的屬性描述符
  const property = Object.getOwnPropertyDescriptor(obj, key)
  // 如果該屬性不可配置則不繼續(xù)執(zhí)行
  if (property && property.configurable === false) {
    return
  }
  // 提供預(yù)定義的存取器函數(shù)
  // cater for pre-defined getter/setters
  const getter = property && property.get
  const setter = property && property.set
  // 如果不存在getter或存在settter,且函數(shù)只傳入2個參數(shù),手動設(shè)置val值
  // 這里主要是Obserber的walk方法里使用的情況,只傳入兩個參數(shù)
  if ((!getter || setter) && arguments.length === 2) {
    val = obj[key]
  }
  // 判斷是否遞歸觀察子對象,并將子對象屬性都轉(zhuǎn)換成存取器,返回子觀察目標(biāo)
  let childOb = !shallow && observe(val)
  // 重新定義屬性
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    // 設(shè)置getter
    get: function reactiveGetter () {
      // 如果預(yù)定義的getter存在則value等于getter調(diào)用的返回值
      // 否則直接賦予屬性值
      const value = getter ? getter.call(obj) : val
      // 如果存在當(dāng)前依賴目標(biāo),即監(jiān)視器對象,則建立依賴
      if (Dep.target) {
        dep.depend()
        // 如果子觀察目標(biāo)存在,建立子對象的依賴關(guān)系
        if (childOb) {
          childOb.dep.depend()
          // 如果屬性是數(shù)組,則特殊處理收集數(shù)組對象依賴
          if (Array.isArray(value)) {
            dependArray(value)
          }
        }
      }
      // 返回屬性值
      return value
    },
    // 設(shè)置setter,接收新值newVal參數(shù)
    set: function reactiveSetter (newVal) {
      // 如果預(yù)定義的getter存在則value等于getter調(diào)用的返回值
      // 否則直接賦予屬性值
      const value = getter ? getter.call(obj) : val
      // 如果新值等于舊值或者新值舊值為null則不執(zhí)行
      /* eslint-disable no-self-compare */
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      // 非生產(chǎn)環(huán)境下如果customSetter存在,則調(diào)用customSetter
      /* eslint-enable no-self-compare */
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter()
      }
      // 如果預(yù)定義setter存在則調(diào)用,否則直接更新新值
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      // 判斷是否遞歸觀察子對象并返回子觀察目標(biāo)
      childOb = !shallow && observe(newVal)
      // 發(fā)布變更通知
      dep.notify()
    }
  })
}


// 下面是單獨(dú)定義并導(dǎo)出的動態(tài)增減屬性時觀測的函數(shù)
// set函數(shù)用來對程序執(zhí)行中動態(tài)添加的屬性進(jìn)行觀察并轉(zhuǎn)換存取器,不詳細(xì)解釋
/**
 * Set a property on an object. Adds the new property and
 * triggers change notification if the property doesn't
 * already exist.
 */
export function set (target: Array<any> | Object, key: any, val: any): any {
  if (process.env.NODE_ENV !== 'production' &&
    (isUndef(target) || isPrimitive(target))
  ) {
    warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)
  }
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    target.length = Math.max(target.length, key)
    target.splice(key, 1, val)
    return val
  }
  if (key in target && !(key in Object.prototype)) {
    target[key] = val
    return val
  }
  const ob = (target: any).__ob__
  if (target._isVue || (ob && ob.vmCount)) {
    process.env.NODE_ENV !== 'production' && warn(
      'Avoid adding reactive properties to a Vue instance or its root $data ' +
      'at runtime - declare it upfront in the data option.'
    )
    return val
  }
  if (!ob) {
    target[key] = val
    return val
  }
  defineReactive(ob.value, key, val)
  ob.dep.notify()
  return val
}

// Delete函數(shù)用來對程序執(zhí)行中動態(tài)刪除的屬性發(fā)布變更通知,不詳細(xì)解釋
/**
 * Delete a property and trigger change if necessary.
 */
export function del (target: Array<any> | Object, key: any) {
  if (process.env.NODE_ENV !== 'production' &&
    (isUndef(target) || isPrimitive(target))
  ) {
    warn(`Cannot delete reactive property on undefined, null, or primitive value: ${(target: any)}`)
  }
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    target.splice(key, 1)
    return
  }
  const ob = (target: any).__ob__
  if (target._isVue || (ob && ob.vmCount)) {
    process.env.NODE_ENV !== 'production' && warn(
      'Avoid deleting properties on a Vue instance or its root $data ' +
      '- just set it to null.'
    )
    return
  }
  if (!hasOwn(target, key)) {
    return
  }
  delete target[key]
  if (!ob) {
    return
  }
  ob.dep.notify()
}

// 特殊處理數(shù)組的依賴收集的函數(shù),遞歸的對數(shù)組中的成員執(zhí)行依賴收集
/**
 * Collect dependencies on array elements when the array is touched, since
 * we cannot intercept array element access like property getters.
 */
function dependArray (value: Array<any>) {
  for (let e, i = 0, l = value.length; i < l; i++) {
    e = value[i]
    e && e.__ob__ && e.__ob__.dep.depend()
    if (Array.isArray(e)) {
      dependArray(e)
    }
  }
}

Dep

let uid = 0

// dep是個可觀察對象,可以有多個指令訂閱它
/**
 * A dep is an observable that can have multiple
 * directives subscribing to it.
 */
// 定義并導(dǎo)出Dep類
export default class Dep {
  // 定義變量
  // 私有變量,當(dāng)前評估watcher對象
  static target: ?Watcher;
  // dep實(shí)例Id
  id: number;
  // dep實(shí)例監(jiān)視器/訂閱者數(shù)組
  subs: Array<Watcher>;

  // 定義構(gòu)造器
  constructor () {
    // 初始化時賦予遞增的id
    this.id = uid++
    this.subs = []
  }

  // 定義addSub方法,接受Watcher類型的sub參數(shù)
  addSub (sub: Watcher) {
    // 向subs數(shù)組里添加新的watcher
    this.subs.push(sub)
  }

  // 定義removeSub方法,接受Watcher類型的sub參數(shù)
  removeSub (sub: Watcher) {
    // 從subs數(shù)組里移除指定watcher
    remove(this.subs, sub)
  }

  // 定義depend方法,將觀察對象和watcher建立依賴
  depend () {
    // 在創(chuàng)建Wacther的時候會將在創(chuàng)建的Watcher賦值給Dep.target
    // 建立依賴時如果存在Watcher,則會調(diào)用Watcher的addDep方法
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

  // 定義notify方法,通知更新
  notify () {
    // 調(diào)用每個訂閱者的update方法實(shí)現(xiàn)更新
    // stabilize the subscriber list first
    const subs = this.subs.slice()
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}

// Dep.target用來存放目前正在評估的watcher
// 全局唯一,并且一次也只能有一個watcher被評估
// 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
// targetStack用來存放watcher棧
const targetStack = []

// 定義并導(dǎo)出pushTarget函數(shù),接受Watcher類型的參數(shù)
export function pushTarget (_target: ?Watcher) {
  // 入棧并將當(dāng)前watcher賦值給Dep.target
  if (Dep.target) targetStack.push(Dep.target)
  Dep.target = _target
}

// 定義并導(dǎo)出popTarget函數(shù)
export function popTarget () {
  // 出棧操作
  Dep.target = targetStack.pop()
}

Watcher

let uid = 0

// watcher用來解析表達(dá)式,收集依賴對象,并在表達(dá)式的值變動時執(zhí)行回調(diào)函數(shù)
// 全局的$watch()方法和指令都以同樣方式實(shí)現(xiàn)
/**
 * 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.
 */
// 定義并導(dǎo)出Watcher類
export default class Watcher {
  // 定義變量
  vm: Component; // 實(shí)例
  expression: string; // 表達(dá)式
  cb: Function; // 回調(diào)函數(shù)
  id: number; // watcher實(shí)例Id
  deep: boolean; // 是否深層依賴
  user: boolean; // 是否用戶定義
  computed: boolean; // 是否計(jì)算屬性
  sync: boolean; // 是否同步
  dirty: boolean;  // 是否為臟監(jiān)視器
  active: boolean; // 是否激活中
  dep: Dep; // 依賴對象
  deps: Array<Dep>; // 依賴對象數(shù)組
  newDeps: Array<Dep>; // 新依賴對象數(shù)組
  depIds: SimpleSet;  // 依賴id集合
  newDepIds: SimpleSet; // 新依賴id集合
  before: ?Function; // 先行調(diào)用函數(shù)
  getter: Function; // 指定getter
  value: any; // 觀察值

  // 定義構(gòu)造函數(shù)
  // 接收vue實(shí)例,表達(dá)式對象,回調(diào)函數(shù),配置對象,是否渲染監(jiān)視器5個參數(shù)
  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    // 下面是對實(shí)例屬性的賦值
    this.vm = vm
    // 如果是渲染監(jiān)視器則將它賦值給實(shí)例的_watcher屬性
    if (isRenderWatcher) {
      vm._watcher = this
    }
    // 添加到vm._watchers數(shù)組中
    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 {
      // 否則將配屬性設(shè)為false
      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()
      : ''
    // 設(shè)置監(jiān)視器的getter方法
    // parse expression for getter
    // 如果傳入的expOrFn參數(shù)是函數(shù)直接賦值給getter屬性
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } else {
      // 否則解析傳入的表達(dá)式的路徑,返回最后一級數(shù)據(jù)對象
      // 這里是支持使用點(diǎn)符號獲取屬性的表達(dá)式來獲取嵌套需觀測數(shù)據(jù)
      this.getter = parsePath(expOrFn)
      // 不存在getter則設(shè)置空函數(shù)
      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
        )
      }
    }
    // 如果是計(jì)算屬性,創(chuàng)建dep屬性
    if (this.computed) {
      this.value = undefined
      // 
      this.dep = new Dep()
    } else {
      // 負(fù)責(zé)調(diào)用get方法獲取觀測值
      this.value = this.get()
    }
  }

  // 評估getter,并重新收集依賴項(xiàng)
  /**
   * Evaluate the getter, and re-collect dependencies.
   */
  get () {
    // 將實(shí)例添加到watcher棧中
    pushTarget(this)
    let value
    const vm = this.vm
    // 嘗試調(diào)用vm的getter方法
    try {
      value = this.getter.call(vm, vm)
    } catch (e) {
      // 捕捉到錯誤時,如果是用戶定義的watcher則處理異常
      if (this.user) {
        handleError(e, vm, `getter for watcher "${this.expression}"`)
      } else {
        // 否則拋出異常
        throw e
      }
    } finally {
      // 最終執(zhí)行“觸摸”每個屬性的操作,以便將它們?nèi)扛櫈樯疃缺O(jiān)視的依賴關(guān)系
      // "touch" every property so they are all tracked as
      // dependencies for deep watching
      if (this.deep) {
        // traverse方法遞歸每一個對象,將對象的每級屬性收集為深度依賴項(xiàng)
        traverse(value)
      }
      // 執(zhí)行出棧
      popTarget()
      // 調(diào)用實(shí)例cleanupDeps方法
      this.cleanupDeps()
    }
    // 返回觀測數(shù)據(jù)
    return value
  }

  // 添加依賴
  /**
   * Add a dependency to this directive.
   */
  // 定義addDep方法,接收Dep類型依賴實(shí)例對象
  addDep (dep: Dep) {
    const id = dep.id
    // 如果不存在依賴,將新依賴對象id和對象添加進(jìn)相應(yīng)數(shù)組中
    if (!this.newDepIds.has(id)) {
      this.newDepIds.add(id)
      this.newDeps.push(dep)
      // 并在dep對象中添加監(jiān)視器自身
      if (!this.depIds.has(id)) {
        dep.addSub(this)
      }
    }
  }

  // 清理依賴項(xiàng)集合
  /**
   * Clean up for dependency collection.
   */
  // 定義cleanupDeps方法
  cleanupDeps () {
    let i = this.deps.length
    // 遍歷依賴列表
    while (i--) {
      const dep = this.deps[i]
      // 如果監(jiān)視器的依賴對象列表中含有當(dāng)前依賴對象
      // 從依賴對象中移除該監(jiān)視器
      if (!this.newDepIds.has(dep.id)) {
        dep.removeSub(this)
      }
    }
    // 重置監(jiān)視器的依賴相關(guān)屬性,
    // 將新建立的依賴轉(zhuǎn)換成常規(guī)依賴
    // 并清空新依賴列表
    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
  }

  // 訂閱者接口,當(dāng)依賴項(xiàng)變更時調(diào)用
  /**
   * Subscriber   .
   * Will be called when a dependency changes.
   */
  // 定義update方法
  update () {
    // 如果是計(jì)算屬性
    /* istanbul ignore else */
    if (this.computed) {
      // 計(jì)算屬性的觀察有兩種模式:懶模式和立即模式
      // 默認(rèn)都設(shè)置為懶模式,要使用立即模式需要至少有一個訂閱者,
      // 典型情況下是另一個計(jì)算屬性或渲染函數(shù)
      // 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.
      // 當(dāng)不存在依賴列表
      if (this.dep.subs.length === 0) {
        // 設(shè)置dirty屬性為true,這是因?yàn)樵趹心J较轮辉谛枰臅r候才執(zhí)行計(jì)算,
        // 所以為了稍后執(zhí)行先把dirty屬性設(shè)置成true,這樣在屬性被訪問的時候
        // 才會執(zhí)行真實(shí)的計(jì)算過程。
        // 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 {
        // 在立即執(zhí)行模式中,需要主動執(zhí)行計(jì)算
        // 但只在值真正變化的時候才通知訂閱者
        // In activated mode, we want to proactively perform the computation
        // but only notify our subscribers when the value has indeed changed.
        // 調(diào)用getAndInvoke函數(shù),判斷是否觀測值真正變化,并發(fā)布更新通知
        this.getAndInvoke(() => {
          this.dep.notify()
        })
      }
    } else if (this.sync) {
      // 如果同步執(zhí)行,則調(diào)用實(shí)例run方法
      this.run()
    } else {
      // 否則將監(jiān)視器添加進(jìn)待評估隊(duì)列
      queueWatcher(this)
    }
  }

  // 調(diào)度工作接口,會被調(diào)度器調(diào)用
  /**
   * Scheduler job interface.
   * Will be called by the scheduler.
   */
  // 定義run方法
  run () {
    // 如果當(dāng)前監(jiān)視器處于活躍狀態(tài),則立即調(diào)用getAndInvoke方法
    if (this.active) {
      this.getAndInvoke(this.cb)
    }
  }

  // 定義getAndInvoke方法,接收一個回調(diào)函數(shù)參數(shù)
  getAndInvoke (cb: Function) {
    // 獲取新觀測值
    const value = this.get()
    // 當(dāng)舊值與新值不相等,或者掛廁紙是對象,或需要深度觀察時
    // 觸發(fā)變更,發(fā)布通知
    if (
      value !== this.value ||
      // 因?yàn)閷ο蠡驍?shù)組即使相等時,其值可能發(fā)生變異所以也需要觸發(fā)更新
      // 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
    ) {
      // 更細(xì)觀測值,并設(shè)置置否dirty屬性
      // set new value
      const oldValue = this.value
      this.value = value
      this.dirty = false
      // 如果是用戶自定義監(jiān)視器,則在調(diào)用回調(diào)函數(shù)時設(shè)置錯誤捕捉
      if (this.user) {
        try {
          cb.call(this.vm, value, oldValue)
        } catch (e) {
          handleError(e, this.vm, `callback for watcher "${this.expression}"`)
        }
      } else {
        cb.call(this.vm, value, oldValue)
      }
    }
  }

  // 評估和返回觀測值方法,只在計(jì)算屬性時被調(diào)用
  /**
   * Evaluate and return the value of the watcher.
   * This only gets called for computed property watchers.
   */
  // 定義evaluate方法
  evaluate () {
    // 如果是計(jì)算屬性,獲取觀測是,并返回
    if (this.dirty) {
      this.value = this.get()
      this.dirty = false
    }
    return this.value
  }

  // 建立監(jiān)視器的依賴方法,只在計(jì)算屬性調(diào)用
  /**
   * Depend on this watcher. Only for computed property watchers.
   */
  // 定義depend方法
  depend () {
    // 如果依賴對象存在且存在當(dāng)前運(yùn)行監(jiān)視器,建立依賴
    if (this.dep && Dep.target) {
      this.dep.depend()
    }
  }

  // 銷毀監(jiān)視器方法,將自身從依賴數(shù)組中移除
  /**
   * Remove self from all dependencies' subscriber list.
   */
  // 定義teardown方法
  teardown () {
    // 當(dāng)監(jiān)視器處于活躍狀態(tài),執(zhí)行銷毀
    if (this.active) {
      // 從監(jiān)視器列表中移除監(jiān)視器是高開銷操作 
      // 所以如果實(shí)例正在銷毀中則跳過銷毀
      // remove self from vm's watcher list
      // this is a somewhat expensive operation so we skip it
      // if the vm is being destroyed.
      // 當(dāng)實(shí)例正常運(yùn)行中,從監(jiān)視器列表中移除監(jiān)視器
      if (!this.vm._isBeingDestroyed) {
        remove(this.vm._watchers, this)
      }
      // 從所有依賴列表中移除該監(jiān)視器
      let i = this.deps.length
      while (i--) {
        this.deps[i].removeSub(this)
      }
      // 將監(jiān)視器的活躍狀態(tài)置否
      this.active = false
    }
  }
}

本篇主要是關(guān)于源碼的解釋,可以翻看觀察系統(tǒng)的原理篇來對照理解。


在這里記錄下了Vue的數(shù)據(jù)綁定具體實(shí)現(xiàn)的源代碼的個人理解,有些細(xì)節(jié)的地方或許還認(rèn)識的不夠充分,觀察系統(tǒng)里的三個類兜兜轉(zhuǎn)轉(zhuǎn),關(guān)聯(lián)性很強(qiáng),在各自的方法中交叉地引用自身與其他類的實(shí)例,很容易讓人頭暈?zāi)垦#还茉鯓?,對于整體功能邏輯有清晰的認(rèn)識,以后便能向更高層面邁進(jìn)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容