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

Vue源碼學(xué)習(xí)之關(guān)于對Array的數(shù)據(jù)偵聽實(shí)現(xiàn)

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

摘要

我們都知道Vue的響應(yīng)式是通過Object.defineProperty來進(jìn)行數(shù)據(jù)劫持。但是那是針對Object類型可以實(shí)現(xiàn), 如果是數(shù)組呢? 通過set/get方式是不行的。

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

核心思想

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

攔截器

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

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

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

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

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

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

關(guān)于Vue什么時(shí)候?qū)ata屬性進(jìn)行Observer

如果熟悉Vue源碼的童鞋應(yīng)該很快能找到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原型綁定三個(gè)實(shí)例方法: vm.$watch,vm.$set,vm.$delete
stateMixin(Vue)
// 給Vue原型綁定事件相關(guān)的實(shí)例方法: vm.$on, vm.$once ,vm.$off , vm.$emit
eventsMixin(Vue)
// 給Vue原型綁定生命周期相關(guān)的實(shí)例方法: vm.$forceUpdate, vm.destroy, 以及私有方法_update
lifecycleMixin(Vue)
// 給Vue原型綁定生命周期相關(guān)的實(shí)例方法: 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) {
  // 當(dāng)前實(shí)例
  const vm: Component = this
  // a uid
  // 實(shí)例唯一標(biāo)識(shí)
  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}`
   // 處于組件初始化階段開始打點(diǎn)
   mark(startTag)
  }

  // a flag to avoid this being observed
  // 標(biāo)識(shí)為一個(gè)Vue實(shí)例
  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)
 }
}

這個(gè)時(shí)候你會(huì)發(fā)現(xiàn)observe出現(xiàn)了。

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已經(jīng)是一個(gè)響應(yīng)式數(shù)據(jù)就不再創(chuàng)建Observe實(shí)例, 避免重復(fù)偵聽
  ob = value.__ob__
 } else if (
  shouldObserve &&
  !isServerRendering() &&
  (Array.isArray(value) || isPlainObject(value)) &&
  Object.isExtensible(value) &&
  !value._isVue
 ) {
  // 出現(xiàn)目標(biāo), 創(chuàng)建一個(gè)Observer實(shí)例
  ob = new Observer(value)
 }
 if (asRootData && ob) {
  ob.vmCount++
 }
 return ob
}

使用攔截器的時(shí)機(jī)

Vue的響應(yīng)式系統(tǒng)中有個(gè)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: 數(shù)組代理原型對象
 // keys: const arrayKeys = Object.getOwnPropertyNames(arrayMethods)
 // keys: 數(shù)組代理原型對象上的幾個(gè)編譯方法名
 // 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)
  // 如果是數(shù)組
  if (Array.isArray(value)) {
   if (hasProto) {
    // 如果支持__proto__屬性(非標(biāo)屬性, 大多數(shù)瀏覽器支持): 直接把原型指向代理原型對象
    protoAugment(value, arrayMethods)
   } else {
    // 不支持就在數(shù)組實(shí)例上掛載被加工處理過的同名的變異方法(且不可枚舉)來進(jìn)行原型對象方法攔截
    // 當(dāng)你訪問一個(gè)對象的方法時(shí)候, 只有當(dāng)自身不存在時(shí)候才會(huì)去原型對象上查找
    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])
  }
 }

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

如何收集依賴

Vue里面真正做數(shù)據(jù)響應(yīng)式處理的是defineReactive()。 defineReactive方法就是把對象的數(shù)據(jù)屬性轉(zhuǎn)為訪問器屬性, 即為數(shù)據(jù)屬性設(shè)置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在訪問器屬性中閉包使用
 // 每一個(gè)數(shù)據(jù)字段都通過閉包引用著屬于自己的 dep 常量
 // 每個(gè)字段的Dep對象都被用來收集那些屬于對應(yīng)字段的依賴。
 const dep = new Dep()

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

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

存儲(chǔ)數(shù)組依賴的列表

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

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

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

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

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

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

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

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

牢記所有的屬性一旦被偵測了都會(huì)被打上一個(gè)__ob__的標(biāo)記, 即表示是響應(yīng)式數(shù)據(jù)。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

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

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

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

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

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

    Vue的data為啥只能是函數(shù)原理詳解

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

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

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

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

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

    Vue中的默認(rèn)插槽詳解

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

    Vue3中ref與reactive的詳解與擴(kuò)展

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

    Vue 中 a標(biāo)簽上href無法跳轉(zhuǎn)的解決方式

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

    vuex中的state、getters、mutations、actions之間的關(guān)系解讀

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

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

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

最新評論