国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

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

2019-11-19 11:43:45
字體:
供稿:網(wǎng)友

摘要

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

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

核心思想

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

攔截器

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

/** * Vue對數(shù)組的變化偵測 * 思想: 通過一個攔截器來覆蓋Array.prototype。 * 攔截器其實就是一個Object, 它的屬性與Array.prototype一樣。 只是對數(shù)組的變異方法進行了處理。*/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í)行后會改變原始數(shù)組的方法const methodsToPatch = [  'push',  'pop',  'shift',  'unshift',  'splice',  'sort',  'reverse']methodsToPatch.forEach(function (method) {  // 緩存原始的數(shù)組原型上的方法  const original = arrayProto[method]  // 對每個數(shù)組編譯方法進行處理(攔截)  def(arrayMethods, method, function mutator (...args) {   // 返回的value還是通過數(shù)組原型方法本身執(zhí)行的結(jié)果   const result = original.apply(this, args)   // 每個value在被observer()時候都會打上一個__ob__屬性   const ob = this.__ob__   // 存儲調(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什么時候?qū)ata屬性進行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原型綁定三個實例方法: vm.$watch,vm.$set,vm.$deletestateMixin(Vue)// 給Vue原型綁定事件相關(guān)的實例方法: vm.$on, vm.$once ,vm.$off , vm.$emiteventsMixin(Vue)// 給Vue原型綁定生命周期相關(guān)的實例方法: vm.$forceUpdate, vm.destroy, 以及私有方法_updatelifecycleMixin(Vue)// 給Vue原型綁定生命周期相關(guān)的實例方法: 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)前實例  const vm: Component = this  // a uid  // 實例唯一標(biāo)識  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  // 標(biāo)識為一個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ā)現(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)是一個響應(yīng)式數(shù)據(jù)就不再創(chuàng)建Observe實例, 避免重復(fù)偵聽  ob = value.__ob__ } else if (  shouldObserve &&  !isServerRendering() &&  (Array.isArray(value) || isPlainObject(value)) &&  Object.isExtensible(value) &&  !value._isVue ) {  // 出現(xiàn)目標(biāo), 創(chuàng)建一個Observer實例  ob = new Observer(value) } if (asRootData && ob) {  ob.vmCount++ } return ob}

使用攔截器的時機

Vue的響應(yīng)式系統(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: 數(shù)組代理原型對象 // keys: const arrayKeys = Object.getOwnPropertyNames(arrayMethods) // keys: 數(shù)組代理原型對象上的幾個編譯方法名 // 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ù)組實例上掛載被加工處理過的同名的變異方法(且不可枚舉)來進行原型對象方法攔截    // 當(dāng)你訪問一個對象的方法時候, 只有當(dāng)自身不存在時候才會去原型對象上查找    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ù)組每一項來進行偵聽變化,即每個元素執(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在訪問器屬性中閉包使用 // 每一個數(shù)據(jù)字段都通過閉包引用著屬于自己的 dep 常量 // 每個字段的Dep對象都被用來收集那些屬于對應(yīng)字段的依賴。 const dep = new Dep() // 獲取該字段可能已有的屬性描述對象 const property = Object.getOwnPropertyDescriptor(obj, key) // 邊界情況處理: 一個不可配置的屬性是不能使用也沒必要使用 Object.defineProperty 改變其屬性定義的。 if (property && property.configurable === false) {  return } // 由于一個對象的屬性很可能已經(jīng)是一個訪問器屬性了,所以該屬性很可能已經(jīng)存在 get 或 set 方法 // 如果接下來會使用 Object.defineProperty 函數(shù)重新定義屬性的 setter/getter // 這會導(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ù)的返回值作為屬性的值,保證屬性的原有讀取操作正常運作   // 如果 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)) {      // 調(diào)用 dependArray 函數(shù)逐個觸發(fā)數(shù)組每個元素的依賴收集      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è)置的新值是一個數(shù)組或者純對象,   // 那么該數(shù)組或純對象是未被觀測的,所以需要對新值進行觀測   childOb = !shallow && observe(newVal)   // 通知dep中的watcher更新   dep.notify()  } })}

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

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

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

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

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

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

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上新增一個不可枚舉的__ob__屬性, 這個屬性的值就是Observer實例    // 因此我們就可以通過數(shù)組數(shù)據(jù)__ob__獲取Observer實例    // 進而獲取__ob__上的dep    def(value, '__ob__', this)    ...  }}

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

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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 开封县| 福安市| 得荣县| 福贡县| 乌海市| 太保市| 清镇市| 丹阳市| 济源市| 诸暨市| 炉霍县| 平乡县| 庆云县| 佛教| 明溪县| 海伦市| 南康市| 任丘市| 晋城| 南阳市| 荆州市| 凤阳县| 屏东市| 察哈| 榆社县| 舒城县| 兴隆县| 阿坝县| 庆安县| 巴里| 大竹县| 南京市| 富平县| 沭阳县| 贺兰县| 北京市| 房产| 九龙县| 定兴县| 隆林| 太湖县|