最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

摘要

我們都知道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.$delete
stateMixin(Vue)
// 給Vue原型綁定事件相關(guān)的實例方法: vm.$on, vm.$once ,vm.$off , vm.$emit
eventsMixin(Vue)
// 給Vue原型綁定生命周期相關(guān)的實例方法: vm.$forceUpdate, vm.destroy, 以及私有方法_update
lifecycleMixin(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
  // 實例唯一標識
  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ā)現(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)目標, 創(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__屬性(非標屬性, 大多數(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]
 }
 // 默認就是深度觀測,引用子屬性的__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__的標記, 即表示是響應(yīng)式數(shù)據(jù)。

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

您可能感興趣的文章:

相關(guān)文章

  • vue自定義指令實現(xiàn)方法詳解

    vue自定義指令實現(xiàn)方法詳解

    這篇文章主要介紹了vue自定義指令實現(xiàn)方法,結(jié)合實例形式分析了vue.js自定義指令相關(guān)定義、注冊、使用方法及操作注意事項,需要的朋友可以參考下
    2019-02-02
  • Vue使用NPM方式搭建項目

    Vue使用NPM方式搭建項目

    這篇文章主要介紹了Vue項目搭建過程,使用NPM方式搭建的,本文分步驟給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下
    2018-10-10
  • vue如何統(tǒng)一樣式(reset.css與border.css)

    vue如何統(tǒng)一樣式(reset.css與border.css)

    這篇文章主要介紹了vue如何統(tǒng)一樣式(reset.css與border.css),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • vue-cli中vue本地實現(xiàn)跨域調(diào)試接口

    vue-cli中vue本地實現(xiàn)跨域調(diào)試接口

    這篇文章主要介紹了vue-cli中vue本地實現(xiàn)跨域調(diào)試接口,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-01-01
  • 詳解VSCode配置啟動Vue項目

    詳解VSCode配置啟動Vue項目

    這篇文章主要介紹了VSCode配置啟動Vue項目,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • 手把手教你將vue前端和python腳本使用electron打包成桌面應(yīng)用程序

    手把手教你將vue前端和python腳本使用electron打包成桌面應(yīng)用程序

    這篇文章主要介紹了如何將Vue項目和Python腳本打包,并將打包后的文件部署到Vue項目中,文中通過代碼以及圖文介紹的非常詳細,需要的朋友可以參考下
    2025-01-01
  • Vue如何實現(xiàn)分批加載數(shù)據(jù)

    Vue如何實現(xiàn)分批加載數(shù)據(jù)

    這篇文章主要介紹了Vue如何實現(xiàn)分批加載數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-04-04
  • vue組件父子間通信詳解(三)

    vue組件父子間通信詳解(三)

    這篇文章主要為大家詳細介紹了vue組件父子間通信的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-11-11
  • <el-button>點擊后如何跳轉(zhuǎn)指定url鏈接

    <el-button>點擊后如何跳轉(zhuǎn)指定url鏈接

    這篇文章主要介紹了<el-button>點擊后如何跳轉(zhuǎn)指定url鏈接問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • vue項目中main.js的用法

    vue項目中main.js的用法

    src/main.js是入口文件,主要作用是初始化vue實例并使用需要的插件, Vue.use()的作用就是讓它里面被注冊的組件能夠被全局使用,本文通過實例代碼介紹vue項目中main.js的用法,感興趣的朋友一起看看吧
    2023-10-10

最新評論

沭阳县| 西乡县| 静安区| 道孚县| 延边| 克什克腾旗| 旅游| 内黄县| 汝阳县| 新田县| 精河县| 绥宁县| 尼木县| 潮州市| 岳阳县| 赞皇县| 射阳县| 乌拉特前旗| 德化县| 平阳县| 永仁县| 丰顺县| 建德市| 彝良县| 百色市| 彩票| 永修县| 新绛县| 腾冲县| 乌审旗| 文山县| 安徽省| 会宁县| 汉中市| 富川| 五华县| 鸡泽县| 平果县| 灵武市| 通许县| 苏尼特右旗|