深さでは公式文書応答原理は、このセクションで見ることができ、通じVueのObject.defineProperty
応答の定義のデータ型は、その後、最終的にはニャーとソースコードレベルで行う方法ですか?
SRC /コア/インスタンス/ state.js
私は単にソースを見つめていました
/**
* 1. 调用initData()方法, 初始化用户传入的 data
* @param {*} vm
*/
function initData (vm: Component) {
let data = vm.$options.data // 拿到用户传入的数据
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
if (!isPlainObject(data)) {
data = {}
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
)
}
// proxy data on instance
// 将所有的key 取出来 存到数组里
// Object.keys() 会把一个对象中的所有的key 取出来,返回一个由这些key组成的数组
const keys = Object.keys(data)
const props = vm.$options.props
const methods = vm.$options.methods
let i = keys.length
while (i--) {
const key = keys[i]
if (process.env.NODE_ENV !== 'production') {
if (methods && hasOwn(methods, key)) {
warn(
`Method "${key}" has already been defined as a data property.`,
vm
)
}
}
if (props && hasOwn(props, key)) {
process.env.NODE_ENV !== 'production' && warn(
`The data property "${key}" is already declared as a prop. ` +
`Use prop default value instead.`,
vm
)
} else if (!isReserved(key)) {
proxy(vm, `_data`, key)
}
}
// observe data
/**
* 2. 就是对数据 进行观测
*/
observe(data, true /* asRootData */)
}
この観察()メソッドで次を見
SRC /コア/観測/ index.js
このコードは、非常に明確な視線で、オブザーバーインスタンスの値を作成しようとしている
、主にフレーズを確認するためにnew Observer(value)
、この観察を渡されるデータを置きますObserver类
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
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) {
ob = value.__ob__
} else if (
shouldObserve &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (asRootData && ob) {
ob.vmCount++
}
return ob
}
そして、見てOberver
クラス
のsrc /コア/観測/ index.js
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)
if (Array.isArray(value)) {
if (hasProto) {
protoAugment(value, arrayMethods)
} else {
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])
}
}
/**
* Observe a list of Array items.
*/
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
このクラスは、判断を下すことが観察されたデータの最初の主要なです
- オブジェクトが、残っている場合は
this.walk(value)
、この方法を
それでは見てthis.walk()
最初にすべてのある方法で、key
配列にし、[すべてのコンビニエンスキーの、呼び出しはdefineReactive()
、この方法では、我々は重要な方法を参照してObject.defineProperty()
、この方法は、キーのすべてに応答を再定義することです与えながら、データが設定されている間、それはまた、呼び出すときに、各キーには、セッターとゲッターを追加するdep.notify()
アップデート方法を
/**
* Define a reactive property on an Object.
*/
export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
const dep = new Dep()
const property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
const getter = property && property.get
const setter = property && property.set
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter()
}
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify()
}
})
}
これらは、オブジェクトのVUE応答扱いされている、それはデータの配列を扱っているか、それを入力します
- 配列は、プロトタイプが上書きされますコピーし、defのメソッドを呼び出すためのメソッドの配列、最後に更新通知がある場合
SRC /コア/観測/ 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)
/**
* 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)
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
})
})
要約:
- 最初の呼び出しinitData()メソッド、すなわち、これらのデータの観察次に、着信データのユーザを初期化し
new Oberser()
、- オブジェクトは、キーの全てを容易にすることである場合、このデータは、その後、オブジェクト、または配列のタイプを決定し、呼び出し
defineReactive()
再定義データは、応答追加、キーセッターとゲッター、多層構造に追加されたとき、再帰的方法- 次いで、アレイ、プロトタイプにコピーの配列方法、およびアレイ法を書き換える場合、DEF()メソッド、決意スイッチ...ケース、最後の更新通知を呼び出します