来不及解释了,快上车......
之前的一篇文章vue2.x响应式原理次要是对象的响应式,明天补充一下数组响应式的原理,因为vue对数组做了特地的解决。
vue为什么没像解决对象一样用Object.defineProperty解决数组?是Object.defineProperty无奈监测数组吗?又或者是出于其它方面的什么思考呢?那它是怎么实现对数组的监听的?带着这些问题咱们去一探到底...
Object.defineProperty反对数组吗
首先咱们来做一个测试,看Object.defineProperty是否反对数组。
function defineReactive(obj, key, val) { Object.defineProperty(obj, key, { enumerable: true, // 属性可枚举 configurable: true, get() { console.log('-----读取', val) return val; }, set(newVal) { if (val === newVal) return val = newVal console.log('-----扭转---', val, obj) } })}
还是这个defineReactive函数,咱们通过它来遍历数组,用数组的索引作为key,来给每一项打上getter/setter。
let array = [1,2,3,4,5]array.forEach((c,index) => { defineReactive(array, index, c)})
咱们在控制台打印一下,能够看到打印的后果,这阐明数组项被打上了getter/setter,还回到这个问题,Object.defineProperty能够做到对数组的监听,它是反对数组的。
vue为什么没有提供对数组属性的监听呢
第二个为题就来了,既然Object.defineProperty有这个能力,那么vue为什么没用它来实现对数组属性的监听呢
有人提到length属性,length属性的扭转可能会导致一些空元素,确实,Object.defineProperty不能解决这些为空的数组。然而咱们换个角度想一下,通过扭转length属性去减少数组长度,不就是相当于减少属性吗,这个在对象外面vue也是无奈监测到的。
在上图第二个log外面,当给数组某一项赋值的时候,触发了setter,setter的时候,数据更新又会调用一遍getter函数,这会影响性能。另外很多时候数组长度咱们并不确定,无奈提前打上getter/setter,而且如果数组长度很大也会造成性能问题,用尤大的原话说就是性能代价和取得的用户体验收益不成正比。
贴一个尤大在github上的答复。
另外贺师俊老湿的答复也十分精辟
:如果你晓得数组的长度,实践上是能够事后给所有的索引设置getter/setter的。然而一来很多场景下你不晓得数组的长度,二来,如果是很大的数组,事后加getter/setter性能累赘较大。
总而言之就是实践上vue是能够这样做,然而出于性能思考没这样做,而是用了一种数组变异方法来触发视图更新。
vue如何实现对数组的监听
解决了下面的两个问题,咱们接下来就来看看vue的数组变异具体是怎么实现的。
const arrayKeys = Object.getOwnPropertyNames(arrayMethods)if (Array.isArray(value)) { const augment = hasProto ? protoAugment : copyAugment augment(value, arrayMethods, arrayKeys) this.observeArray(value)} else { this.walk(value)}
observeArray会把数组外面的对象数据变成是可侦测的响应式数据,observeArray和walk函数次要还是咱们上篇文章vue2.x响应式原理的内容。vue在这里对数组进行了特地解决,就是依附着protoAugment、copyAugment这两个函数。
export const hasProto = '__proto__' in {}
首先通过hasProto判断浏览器是否反对__proto__属性,来决定是执行protoAugment还是copyAugment。再看这两个函数之前,咱们先来看一下数组变异的外围文件array.js,顺便也能晓得arrayMethods, arrayKeys这两个参数是什么。
// array.jsimport { def } from '../util/index'const arrayProto = Array.prototypeexport const arrayMethods = Object.create(arrayProto)/** * Intercept mutating methods and emit events */;[ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'].forEach(function (method) { // cache original method const original = arrayProto[method] def(arrayMethods, method, function mutator (...args) { // 调用数组真正的办法 const result = original.apply(this, args) // __ob__代表数据是否被observe了 const ob = this.__ob__ let inserted switch (method) { case 'push': case 'unshift': inserted = args break case 'splice': inserted = args.slice(2) break } // inserted示意有数据插入 对新数据进行observe if (inserted) ob.observeArray(inserted) // notify change ob.dep.notify() return result })})
/** * Define a property. */export function def (obj: Object, key: string, val:any,enumerable?:boolean) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true })}
vue通过Object.create让arrayMethods继承了数组的原型,Object.create实质是原型式继承【手撕JS继承】,此时数组的原型挂到了arrayMethods的原型链上。
def函数次要来定义属性。遍历这七种办法,通过def函数,咱们重写了arrayMethods原型链上的这七种办法,并在外部调用了数组的原始办法,最初通过notify更新视图。inserted代表新数据插入,须要对新数据进行obsserve。
上面咱们再回头来看protoAugment贺copyAugment这两个函数。
/** * 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]) }}
protoAugment让数组的原型链指向了arrayMethods。
当浏览器不反对__proto__
时候,遍历arrayKeys,通过def函数,咱们手动把arrayMethods上的办法挂载到指标数据上,相当于是个polyfill。惟一的区别是protoAugment是把arrayMethods挂到了指标的原型链上,而copyAugment则是间接把arrayMethods的办法定义到了指标的属性上。
## 小结
vue出于性能的思考,没有用Object.defineProperty去监听数组,而是通过笼罩数组的原型的办法,对罕用的七种办法进行了变异,以此来实现对数组的监听。
源码地址