欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue源碼學習之關于對Array的數據偵聽實現

 更新時間:2019年04月23日 09:28:14   作者:小諾哥  
這篇文章主要介紹了Vue源碼學習之關于對Array的數據偵聽實現,Vue使用了一個方式來實現Array類型的監(jiān)測就是攔截器,具有一定的參考價值,感興趣的小伙伴們可以參考一下

摘要

我們都知道Vue的響應式是通過Object.defineProperty來進行數據劫持。但是那是針對Object類型可以實現, 如果是數組呢? 通過set/get方式是不行的。

但是Vue作者使用了一個方式來實現Array類型的監(jiān)測: 攔截器。

核心思想

通過創(chuàng)建一個攔截器來覆蓋數組本身的原型對象Array.prototype。

攔截器

通過查看Vue源碼路徑vue/src/core/observer/array.js。

/**
 * Vue對數組的變化偵測
 * 思想: 通過一個攔截器來覆蓋Array.prototype。
 * 攔截器其實就是一個Object, 它的屬性與Array.prototype一樣。 只是對數組的變異方法進行了處理。
*/

function def (obj, key, val, enumerable) {
  Object.defineProperty(obj, key, {
   value: val,
   enumerable: !!enumerable,
   writable: true,
   configurable: true
  })
}

// 數組原型對象
const arrayProto = Array.prototype
// 攔截器
const arrayMethods = Object.create(arrayProto)

// 變異數組方法:執(zhí)行后會改變原始數組的方法
const methodsToPatch = [
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
]

methodsToPatch.forEach(function (method) {
  // 緩存原始的數組原型上的方法
  const original = arrayProto[method]
  // 對每個數組編譯方法進行處理(攔截)
  def(arrayMethods, method, function mutator (...args) {
   // 返回的value還是通過數組原型方法本身執(zhí)行的結果
   const result = original.apply(this, args)
   // 每個value在被observer()時候都會打上一個__ob__屬性
   const ob = this.__ob__
   // 存儲調用執(zhí)行變異數組方法導致數組本身值改變的數組,主要指的是原始數組增加的那部分(需要重新Observer)
   let inserted
   switch (method) {
    case 'push':
    case 'unshift':
     inserted = args
     break
    case 'splice':
     inserted = args.slice(2)
     break
   }
   // 重新Observe新增加的數組元素
   if (inserted) ob.observeArray(inserted)
   // 發(fā)送變化通知
   ob.dep.notify()
   return result
  })
})

關于Vue什么時候對data屬性進行Observer

如果熟悉Vue源碼的童鞋應該很快能找到Vue的入口文件vue/src/core/instance/index.js。

function Vue (options) {
 if (process.env.NODE_ENV !== 'production' &&
  !(this instanceof Vue)
 ) {
  warn('Vue is a constructor and should be called with the `new` keyword')
 }
 this._init(options)
}

initMixin(Vue)
// 給原型綁定代理屬性$props, $data
// 給Vue原型綁定三個實例方法: vm.$watch,vm.$set,vm.$delete
stateMixin(Vue)
// 給Vue原型綁定事件相關的實例方法: vm.$on, vm.$once ,vm.$off , vm.$emit
eventsMixin(Vue)
// 給Vue原型綁定生命周期相關的實例方法: vm.$forceUpdate, vm.destroy, 以及私有方法_update
lifecycleMixin(Vue)
// 給Vue原型綁定生命周期相關的實例方法: vm.$nextTick, 以及私有方法_render, 以及一堆工具方法
renderMixin(Vue)

export default Vue

this.init()

源碼路徑: vue/src/core/instance/init.js。

export function initMixin (Vue: Class<Component>) {
 Vue.prototype._init = function (options?: Object) {
  // 當前實例
  const vm: Component = this
  // a uid
  // 實例唯一標識
  vm._uid = uid++

  let startTag, endTag
  /* istanbul ignore if */
  // 開發(fā)模式, 開啟Vue性能檢測和支持 performance.mark API 的瀏覽器上。
  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
   startTag = `vue-perf-start:${vm._uid}`
   endTag = `vue-perf-end:${vm._uid}`
   // 處于組件初始化階段開始打點
   mark(startTag)
  }

  // a flag to avoid this being observed
  // 標識為一個Vue實例
  vm._isVue = true
  // merge options
  // 把我們傳入的optionsMerge到$options
  if (options && options._isComponent) {
   // optimize internal component instantiation
   // since dynamic options merging is pretty slow, and none of the
   // internal component options needs special treatment.
   initInternalComponent(vm, options)
  } else {
   vm.$options = mergeOptions(
    resolveConstructorOptions(vm.constructor),
    options || {},
    vm
   )
  }
  /* istanbul ignore else */
  if (process.env.NODE_ENV !== 'production') {
   initProxy(vm)
  } else {
   vm._renderProxy = vm
  }
  // expose real self
  vm._self = vm
  // 初始化生命周期
  initLifecycle(vm)
  // 初始化事件中心
  initEvents(vm)
  initRender(vm)
  callHook(vm, 'beforeCreate')
  initInjections(vm) // resolve injections before data/props
  // 初始化State
  initState(vm)
  initProvide(vm) // resolve provide after data/props
  callHook(vm, 'created')

  /* istanbul ignore if */
  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
   vm._name = formatComponentName(vm, false)
   mark(endTag)
   measure(`vue ${vm._name} init`, startTag, endTag)
  }
  // 掛載
  if (vm.$options.el) {
   vm.$mount(vm.$options.el)
  }
 }
}

initState()

源碼路徑:vue/src/core/instance/state.js。

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

這個時候你會發(fā)現observe出現了。

observe

源碼路徑: vue/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) {
  // value已經是一個響應式數據就不再創(chuàng)建Observe實例, 避免重復偵聽
  ob = value.__ob__
 } else if (
  shouldObserve &&
  !isServerRendering() &&
  (Array.isArray(value) || isPlainObject(value)) &&
  Object.isExtensible(value) &&
  !value._isVue
 ) {
  // 出現目標, 創(chuàng)建一個Observer實例
  ob = new Observer(value)
 }
 if (asRootData && ob) {
  ob.vmCount++
 }
 return ob
}

使用攔截器的時機

Vue的響應式系統(tǒng)中有個Observe類。源碼路徑:vue/src/core/observer/index.js。

// can we use __proto__?
export const hasProto = '__proto__' in {}

const arrayKeys = Object.getOwnPropertyNames(arrayMethods)

function protoAugment (target, src: Object) {
 /* eslint-disable no-proto */
 target.__proto__ = src
 /* eslint-enable no-proto */
}

function copyAugment (target: Object, src: Object, keys: Array<string>) {
 // target: 需要被Observe的對象
 // src: 數組代理原型對象
 // keys: const arrayKeys = Object.getOwnPropertyNames(arrayMethods)
 // keys: 數組代理原型對象上的幾個編譯方法名
 // const methodsToPatch = [
 //  'push',
 //  'pop',
 //  'shift',
 //  'unshift',
 //  'splice',
 //  'sort',
 //  'reverse'
 // ]
 for (let i = 0, l = keys.length; i < l; i++) {
  const key = keys[i]
  def(target, key, src[key])
 }
}

export class Observer {
 value: any;
 dep: Dep;
 vmCount: number; // number of vms that have this object as root $data

 constructor (value: any) {
  this.value = value
  // 
  this.dep = new Dep()
  this.vmCount = 0
  def(value, '__ob__', this)
  // 如果是數組
  if (Array.isArray(value)) {
   if (hasProto) {
    // 如果支持__proto__屬性(非標屬性, 大多數瀏覽器支持): 直接把原型指向代理原型對象
    protoAugment(value, arrayMethods)
   } else {
    // 不支持就在數組實例上掛載被加工處理過的同名的變異方法(且不可枚舉)來進行原型對象方法攔截
    // 當你訪問一個對象的方法時候, 只有當自身不存在時候才會去原型對象上查找
    copyAugment(value, arrayMethods, arrayKeys)
   }
   this.observeArray(value)
  } else {
   this.walk(value)
  }
 }

 /**
  * Walk through all properties 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++) {
   defineReactive(obj, keys[i])
  }
 }

 /**
  * 遍歷數組每一項來進行偵聽變化,即每個元素執(zhí)行一遍Observer()
  */
 observeArray (items: Array<any>) {
  for (let i = 0, l = items.length; i < l; i++) {
   observe(items[i])
  }
 }
}

如何收集依賴

Vue里面真正做數據響應式處理的是defineReactive()。 defineReactive方法就是把對象的數據屬性轉為訪問器屬性, 即為數據屬性設置get/set。

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


export function defineReactive (
 obj: Object,
 key: string,
 val: any,
 customSetter?: ?Function,
 shallow?: boolean
) {
 // dep在訪問器屬性中閉包使用
 // 每一個數據字段都通過閉包引用著屬于自己的 dep 常量
 // 每個字段的Dep對象都被用來收集那些屬于對應字段的依賴。
 const dep = new Dep()

 // 獲取該字段可能已有的屬性描述對象
 const property = Object.getOwnPropertyDescriptor(obj, key)
 // 邊界情況處理: 一個不可配置的屬性是不能使用也沒必要使用 Object.defineProperty 改變其屬性定義的。
 if (property && property.configurable === false) {
  return
 }

 // 由于一個對象的屬性很可能已經是一個訪問器屬性了,所以該屬性很可能已經存在 get 或 set 方法
 // 如果接下來會使用 Object.defineProperty 函數重新定義屬性的 setter/getter
 // 這會導致屬性原有的 set 和 get 方法被覆蓋,所以要將屬性原有的 setter/getter 緩存
 const getter = property && property.get
 const setter = property && property.set
 // 邊界情況處理
 if ((!getter || setter) && arguments.length === 2) {
  val = obj[key]
 }
 // 默認就是深度觀測,引用子屬性的__ob__
 // 為Vue.set 或 Vue.delete 方法提供觸發(fā)依賴。
 let childOb = !shallow && observe(val)
 Object.defineProperty(obj, key, {
  enumerable: true,
  configurable: true,
  get: function reactiveGetter () {
   // 如果 getter 存在那么直接調用該函數,并以該函數的返回值作為屬性的值,保證屬性的原有讀取操作正常運作
   // 如果 getter 不存在則使用 val 作為屬性的值
   const value = getter ? getter.call(obj) : val
   // Dep.target的值是在對Watch實例化時候賦值的
   if (Dep.target) {
    // 開始收集依賴到dep
    dep.depend()
    if (childOb) {
     childOb.dep.depend()
     if (Array.isArray(value)) {
      // 調用 dependArray 函數逐個觸發(fā)數組每個元素的依賴收集
      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()
   }
   // #7981: for accessor properties without setter
   if (getter && !setter) return
   // 如果數據之前有setter, 那么應該繼續(xù)使用該函數來設置屬性的值
   if (setter) {
    setter.call(obj, newVal)
   } else {
    // 賦新值
    val = newVal
   }
   // 由于屬性被設置了新的值,那么假如我們?yōu)閷傩栽O置的新值是一個數組或者純對象,
   // 那么該數組或純對象是未被觀測的,所以需要對新值進行觀測
   childOb = !shallow && observe(newVal)
   // 通知dep中的watcher更新
   dep.notify()
  }
 })
}

存儲數組依賴的列表

我們?yōu)槭裁葱枰岩蕾嚧嬖贠bserver實例上。 即

export class Observer {
  constructor (value: any) {
    ...
    this.dep = new Dep()
  }
}

首先我們需要在getter里面訪問到Observer實例

// 即上述的
let childOb = !shallow && observe(val)
...
if (childOb) {
 // 調用Observer實例上dep的depend()方法收集依賴
 childOb.dep.depend()
 if (Array.isArray(value)) {
  // 調用 dependArray 函數逐個觸發(fā)數組每個元素的依賴收集
  dependArray(value)
 }
}

另外我們在前面提到的攔截器中要使用Observer實例。

methodsToPatch.forEach(function (method) {
  ...
  // this表示當前被操作的數據
  // 但是__ob__怎么來的?
  const ob = this.__ob__
  ...
  // 重新Observe新增加的數組元素
  if (inserted) ob.observeArray(inserted)
  // 發(fā)送變化通知
  ob.dep.notify()
  ...
})

思考上述的this.__ob__屬性來自哪里?

export class Observer {
  constructor () {
    ...
    this.dep = new Dep()
    // 在vue上新增一個不可枚舉的__ob__屬性, 這個屬性的值就是Observer實例
    // 因此我們就可以通過數組數據__ob__獲取Observer實例
    // 進而獲取__ob__上的dep
    def(value, '__ob__', this)
    ...
  }
}

牢記所有的屬性一旦被偵測了都會被打上一個__ob__的標記, 即表示是響應式數據。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:

相關文章

  • Vue.js實戰(zhàn)之利用vue-router實現跳轉頁面

    Vue.js實戰(zhàn)之利用vue-router實現跳轉頁面

    對于單頁應用,官方提供了vue-router進行路由跳轉的處理,這篇文章主要給大家介紹了Vue.js實戰(zhàn)之利用vue-router實現跳轉頁面的相關資料,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-04-04
  • 使用Vue生成動態(tài)表單

    使用Vue生成動態(tài)表單

    這篇文章主要介紹了Vue生成動態(tài)表單功能,這是小編第一次接這個需求,作為前端開發(fā)的我真的不知如何下手,今天小編通過一段代碼給大家分享vue生成動態(tài)表單效果,需要的朋友可以參考下
    2019-11-11
  • Vue的data為啥只能是函數原理詳解

    Vue的data為啥只能是函數原理詳解

    這篇文章主要為大家介紹了Vue的data為啥只能是函數原理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-10-10
  • 基于Vue中的父子傳值問題解決

    基于Vue中的父子傳值問題解決

    這篇文章主要介紹了基于Vue中的父子傳值問題解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-07-07
  • vue resource發(fā)送請求的幾種方式

    vue resource發(fā)送請求的幾種方式

    這篇文章主要介紹了vue resource發(fā)送請求的幾種方式,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-09-09
  • Vue中的默認插槽詳解

    Vue中的默認插槽詳解

    在 Vue 中,插槽(Slot)是一種非常強大且靈活的機制,用于在組件中插入內容,默認插槽是在父組件中傳遞內容給子組件時使用的一種方式,這篇文章主要介紹了Vue中的默認插槽詳解,需要的朋友可以參考下
    2024-01-01
  • Vue3中ref與reactive的詳解與擴展

    Vue3中ref與reactive的詳解與擴展

    在vue3中對響應式數據的聲明官方給出了ref()和reactive()這兩種方式,下面這篇文章主要給大家介紹了關于Vue3中ref與reactive的相關資料,需要的朋友可以參考下
    2021-06-06
  • Vue 中 a標簽上href無法跳轉的解決方式

    Vue 中 a標簽上href無法跳轉的解決方式

    今天小編大家分享一篇Vue 中 a標簽上href無法跳轉的解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • vuex中的state、getters、mutations、actions之間的關系解讀

    vuex中的state、getters、mutations、actions之間的關系解讀

    這篇文章主要介紹了vuex中的state、getters、mutations、actions之間的關系,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • vue3使用vis繪制甘特圖制作timeline可拖動時間軸及時間軸中文化(推薦)

    vue3使用vis繪制甘特圖制作timeline可拖動時間軸及時間軸中文化(推薦)

    這篇文章主要介紹了vue3使用vis繪制甘特圖制作timeline可拖動時間軸,時間軸中文化,本文結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-02-02

最新評論