vue监听数组变化的源码inserted = args.slice(2),为什么要slice(2)?
/*
- not type checking this file because flow doesn't play well with
- dynamically accessing methods on Array prototype
*/
import { def } from '../util/index'
const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)
const methodsToPatch = [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
/**
- Intercept mutating methods and emit events
*/
methodsToPatch.forEach(function (method) {
// cache original method
const original = arrayProto[method]
def(arrayMethods, method, function mutator (...args) {
const result = original.apply(this, args)const ob = this.__ob__
let inserted
switch (method) {
case 'push':
case 'unshift':
inserted = args
break
case 'splice':
inserted = args.slice(2)
break
}
if (inserted) ob.observeArray(inserted)
// notify change
ob.dep.notify()
return result
})
})
这里的inserted = args.slice(2),为什么要slice(2)?
回答:
splice 前俩个参数是被替换的位置和长度,第三个参数开始是新增的被插入的值。
做响应式监听的时候,主要是为了对新增加的值做监听,所以拿到slice(2) 就拿到了新增加的数据项,执行ob.observeArray(inserted)就可以了
以上是 vue监听数组变化的源码inserted = args.slice(2),为什么要slice(2)? 的全部内容, 来源链接: utcz.com/p/935772.html