Open Cosen95 opened 4 years ago
Vue中检测数组变化核心有两点:
Vue
data
api
这里用一张流程图来说明:
这里第一步和第二步和上题请说一下响应式数据的原理?是相同的,就不展开说明了。
请说一下响应式数据的原理?
src/core/instance/state.js
initData
src/core/observer/index.js
if (hasProto) { protoAugment(value, arrayMethods) } else { // ... }
也就是protoAugment方法:
protoAugment
/** * Augment a target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src: Object) { /* eslint-disable no-proto */ target.__proto__ = src /* eslint-enable no-proto */ }
src/core/observer/array.js
/* * 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' ]
/**
Vue
中检测数组变化核心有两点:Vue
将data
中的数组,进行了原型链重写。指向了自己定义的数组原型方法,这样当调用数组api
时,就可以通知依赖更新。如果数组中包含着引用类型,会对数组中的引用类型再次进行观测。这里用一张流程图来说明:
src/core/instance/state.js
的112行的initData
函数。src/core/observer/index.js
的124行。src/core/observer/index.js
的49行。也就是
protoAugment
方法:src/core/observer/array.js
。import { def } from '../util/index'
const arrayProto = Array.prototype export const arrayMethods = Object.create(arrayProto)
const methodsToPatch = [ // 这里列举的数组的方法是调用后能改变原数组的 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ]
/**