本篇代碼位於vue/src/core/instance/state.jshtml
繼續隨着核心類的初始化展開探索其餘的模塊,這一篇來研究一下Vue的狀態初始化。這裏的狀態初始化指的就是在建立實例的時候,在配置對象裏定義的屬性、數據變量、方法等是如何進行初始處理的。因爲隨後的數據更新變更都交給觀察系統來負責,因此在事先弄明白了數據綁定的原理以後,就只須要將目光集中在這一部分。vue
來仔細看看在覈心類中首先執行的關於 state
部分的源碼:git
// 定義並導出initState函數,接收參數vm
export function initState (vm: Component) {
// 初始化實例的私有屬性_watchers
// 這就是在觀察系統裏會使用到的存儲全部顯式監視器的對象
vm._watchers = []
// 獲取實例的配置對象
const opts = vm.$options
// 若是定義了props,則初始化props
if (opts.props) initProps(vm, opts.props)
// 若是定義了methods,則初始化methods
if (opts.methods) initMethods(vm, opts.methods)
// 若是定義了data,則初始化data
if (opts.data) {
initData(vm)
} else {
// 不然初始化實例的私有屬性_data爲空對象,並開啓觀察
observe(vm._data = {}, true /* asRootData */)
}
// 若是定義了computed,則初始化計算屬性
if (opts.computed) initComputed(vm, opts.computed)
// 若是定義了watch而且不是nativeWatch,則初始化watch
// nativeWatch是火狐瀏覽器下定義的對象的原型方法
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
複製代碼
這段代碼很是直白,主要用來執行配置對象裏定義的了狀態的初始化。這裏分別有 props
、data
、methods
、computed
、watch
五個配置對象,分別有各自的初始化方法。在仔細研究它們的具體實現以前,先來看一段將在各個初始化函數裏用到的輔助函數。github
// 定義共享屬性定義描述符對象sharedPropertyDefinition
// 描述符對象的枚舉和可配置屬性都設置爲true
// get、set方法設置爲空函數
const sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
}
// 定義並導出proxy函數,該函數用來爲在目標對象上定義並代理屬性
// 接收目標對象target,路徑鍵名sourceKey,屬性鍵名三個參數
export function proxy (target: Object, sourceKey: string, key: string) {
// 設置屬性描述符對象的get方法
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
}
// 設置屬性描述性對象的set犯法
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val
}
// 在目標對象上定義屬性
Object.defineProperty(target, key, sharedPropertyDefinition)
}
複製代碼
proxy
函數的定義很是重要,在下面要探究的各個初始化函數中它,它會將咱們在配置對象中設置的屬性所有定義到實例對象中,可是咱們對這些屬性的操做是經過各部分相應的代理屬性上來執行的。get
和 set
方法的實現很是明白的表示出這一過程,而後再將屬性定義到實例中。由這個函數做爲基礎,繼續來看看其餘五個狀態的初始化函數的內容。數組
// 定義initProps函數,接收vm,propsOptions兩個參數
function initProps (vm: Component, propsOptions: Object) {
// 賦值propsData,propsData是全局擴展傳入的賦值對象
// 在使用extend的時候會用到,實際開發裏運用較少
const propsData = vm.$options.propsData || {}
// 定義實例的_props私有屬性,並賦值給props
const props = vm._props = {}
// 緩存prop鍵,以便未來props更新可使用Array而不是動態對象鍵枚舉進行迭代。
// cache prop keys so that future props updates can iterate using Array
// instead of dynamic object key enumeration.
const keys = vm.$options._propKeys = []
// 是不是根實例
const isRoot = !vm.$parent
// 對於非根實例,關閉觀察標識
// root instance props should be converted
if (!isRoot) {
toggleObserving(false)
}
// 遍歷props配置對象
for (const key in propsOptions) {
// 向緩存鍵值數組中添加鍵名
keys.push(key)
// 驗證prop的值,validateProp執行對初始化定義的props的類型檢查和默認賦值
// 若是有定義類型檢查,布爾值沒有默認值時會被賦予false,字符串默認undefined
// 對propsOptions的比較也是在使用extend擴展時纔有意義
// 具體實現能夠參考 src/core/util/props.js,沒有難點這裏不詳細解釋
const value = validateProp(key, propsOptions, propsData, vm)
// 非生產環境下進行檢查和提示
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
// 進行鍵名的轉換,將駝峯式轉換成連字符式的鍵名
const hyphenatedKey = hyphenate(key)
// 對與保留變量名衝突的鍵名給予提示
if (isReservedAttribute(hyphenatedKey) ||
config.isReservedAttr(hyphenatedKey)) {
warn(
`"${hyphenatedKey}" is a reserved attribute and cannot be used as component prop.`,
vm
)
}
// 對屬性創建觀察,並在直接使用屬性時給予警告
defineReactive(props, key, value, () => {
if (vm.$parent && !isUpdatingChildComponent) {
warn(
`Avoid mutating a prop directly since the value will be ` +
`overwritten whenever the parent component re-renders. ` +
`Instead, use a data or computed property based on the prop's ` +
`value. Prop being mutated: "${key}"`,
vm
)
}
})
} else {
// 非生產環境下直接對屬性進行存取器包裝,創建依賴觀察
defineReactive(props, key, value)
}
// 使用Vue.extend()方法擴展屬性時,已經對靜態屬性進行了代理
// 這裏只須要針對實例化時的屬性執行代理操做
// static props are already proxied on the component's prototype
// during Vue.extend(). We only need to proxy props defined at
// instantiation here.
// 當實例上沒有同名屬性時,對屬性進行代理操做
// 將對鍵名的引用指向vm._props對象中
if (!(key in vm)) {
proxy(vm, `_props`, key)
}
}
// 開啓觀察狀態標識
toggleObserving(true)
}
複製代碼
initProps
函數的最主要內容有兩點,一是對定義的數據創建觀察,二是對數據進行代理,這就是私有變量 _props
的做用,以後獲取和設置的變量都是做爲 _props
的屬性被操做。瀏覽器
另外初始化 props
的過程當中有針對 extend
方法會使用到的 propsData
屬性的初始化。具體使用是在擴展對象時定義一些 props,而後在建立實例的過程當中傳入 propsData 配置對象,擴展對象裏相應的props屬性會接收 propsData 傳入的值。與在父組件傳入 props 的值相似,只是這裏要顯式的經過 propsData
配置對象來傳入值。緩存
// 定義initData函數
function initData (vm: Component) {
// 獲取配置對象的data屬性
let data = vm.$options.data
// 判斷data是不是函數
// 如果函數則將getData函數的返回賦值給data和實例私有屬性_data
// 不然直接將data賦值給實例_data屬性,並在無data時賦值空對象
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
// 若是data不是對象則將data賦值爲空對象
// 進一步保證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
)
}
// 實例對象代理data
// proxy data on instance
// 獲取全部data鍵值
const keys = Object.keys(data)
// 獲取配置對象的props
const props = vm.$options.props
// 獲取配置對象的methods
const methods = vm.$options.methods
// 遍歷keys
let i = keys.length
while (i--) {
const key = keys[i]
// 非生產環境給出與methods定義的方法名衝突的警告
if (process.env.NODE_ENV !== 'production') {
if (methods && hasOwn(methods, key)) {
warn(
`Method "${key}" has already been defined as a data property.`,
vm
)
}
}
// 檢測是否與props衝突
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
)
// 沒有與props衝突而且非保留字時,代理鍵名到實例的_data對象上
} else if (!isReserved(key)) {
proxy(vm, `_data`, key)
}
}
// 觀察數據
// observe data
observe(data, true /* asRootData */)
}
// 定義並導出getData函數,接受函數類型的data對象,和Vue實例對象
export function getData (data: Function, vm: Component): any {
// pushTarget和popTarget是爲了解決Vue依賴性檢測的缺陷可能致使冗餘依賴性的問題
// 具體可參閱 https://github.com/vuejs/vue/issues/7573
// 此操做會設置Dep.target爲undefined,在初始化option時調用dep.depend()也不會創建依賴
// #7573 調用數據getter時禁用dep集合
// #7573 disable dep collection when invoking data getters
pushTarget()
// 嘗試在vm上調用data函數並返回執行結果
try {
return data.call(vm, vm)
} catch (e) {
// 若是捕獲到錯誤則處理錯誤,並返回空對象
handleError(e, vm, `data()`)
return {}
} finally {
popTarget()
}
}
複製代碼
與 props 的處理相似,initData
函數的做用也是爲了對數據創建觀察的依賴關係,而且代理數據到私有變量 _data
上,另外包括了對 data 與其餘配置對象屬性的鍵名衝突的檢測。服務器
// 設置computedWatcherOptions對象
const computedWatcherOptions = { computed: true }
// 定義initComputed函數,接受實例vm,和computed對象
function initComputed (vm: Component, computed: Object) {
// $flow-disable-line
// 定義watchers和實例_computedWatchers屬性,初始賦值空對象
const watchers = vm._computedWatchers = Object.create(null)
// 是不是服務器渲染,computed屬性在服務器渲染期間只能是getter
// computed properties are just getters during SSR
const isSSR = isServerRendering()
// 遍歷computed
for (const key in computed) {
// 獲取用戶定義的值
const userDef = computed[key]
// 若是用戶定義的是函數則賦值給getter不然j將userDef.get方法賦值給getter
const getter = typeof userDef === 'function' ? userDef : userDef.get
// 非生產環境拋出缺乏計算屬性錯誤警告
if (process.env.NODE_ENV !== 'production' && getter == null) {
warn(
`Getter is missing for computed property "${key}".`,
vm
)
}
// 非服務器渲染下
if (!isSSR) {
// 爲計算屬性建立內部監視器
// create internal watcher for the computed property.
watchers[key] = new Watcher(
vm,
getter || noop,
noop,
computedWatcherOptions
)
}
// 組件定義的內部計算屬性已經在組件的原型上定義好了
// 因此這裏只要關注實例初始化時用戶定義的計算屬性
// component-defined computed properties are already defined on the
// component prototype. We only need to define computed properties defined
// at instantiation here.
// 鍵名非實例根屬性時,定義計算屬性,具體參照defineComputed函數
if (!(key in vm)) {
defineComputed(vm, key, userDef)
// 非生產環境下,檢測與data屬性名的衝突並給出警告
} else if (process.env.NODE_ENV !== 'production') {
if (key in vm.$data) {
warn(`The computed property "${key}" is already defined in data.`, vm)
} else if (vm.$options.props && key in vm.$options.props) {
warn(`The computed property "${key}" is already defined as a prop.`, vm)
}
}
}
}
// 定義並導出defineComputed哈數
// 接收實例target,計算屬性鍵名key,計算屬性值userDef參數
export function defineComputed ( target: any, key: string, userDef: Object | Function ) {
// 在非服務器渲染下設置緩存
const shouldCache = !isServerRendering()
// 計算屬性值是函數時
if (typeof userDef === 'function') {
// 設置計算屬性的getter,setter爲空函數
sharedPropertyDefinition.get = shouldCache
? createComputedGetter(key)
: userDef
sharedPropertyDefinition.set = noop
} else {
// 當計算屬性是對象時,設置計算屬性的getter和setter
sharedPropertyDefinition.get = userDef.get
? shouldCache && userDef.cache !== false
? createComputedGetter(key)
: userDef.get
: noop
sharedPropertyDefinition.set = userDef.set
? userDef.set
: noop
}
// 非生產環境下,若是沒喲定義計算屬性的setter
// 想設置計算屬性時給出警告
if (process.env.NODE_ENV !== 'production' &&
sharedPropertyDefinition.set === noop) {
sharedPropertyDefinition.set = function () {
warn(
`Computed property "${key}" was assigned to but it has no setter.`,
this
)
}
}
// 以從新設置的屬性描述符爲基礎在實例對象上定義計算屬性
Object.defineProperty(target, key, sharedPropertyDefinition)
}
// 定義createComputedGetter,建立計算屬性getter
// 目的是在非服務器渲染狀況下創建計算屬性的觀察依賴,
// 並根據其依賴屬性返回計算後的值
function createComputedGetter (key) {
return function computedGetter () {
const watcher = this._computedWatchers && this._computedWatchers[key]
if (watcher) {
watcher.depend()
return watcher.evaluate()
}
}
}
複製代碼
計算屬性的初始化相對複雜一些,首先要對計算屬性創建觀察,而後再在實例上從新定義計算屬性,而且執行屬性代理。因爲加入了服務器渲染的功能,在定義計算屬性的時候對使用環境作判斷,是非服務器渲染會影響到計算屬性的定義,這是因爲服務器渲染下使用框架時,計算屬性是不提供 setter 的;另外也要根據用戶定義的值是函數或者對象來對計算屬性從新定義 getter 和 setter。從這段代碼裏能夠看出一個很是重要的程序,即在獲取計算屬性的時候纔去計算它的值,這正是懶加載的實現。框架
// 定義initMethods方法,接受實例vm,配置屬性methods
function initMethods (vm: Component, methods: Object) {
// 獲取實例的props
const props = vm.$options.props
// 遍歷methods對象
for (const key in methods) {
// 非生產環境下給出警告
if (process.env.NODE_ENV !== 'production') {
// 未賦值方法警告
if (methods[key] == null) {
warn(
`Method "${key}" has an undefined value in the component definition. ` +
`Did you reference the function correctly?`,
vm
)
}
// 與props屬性名衝突警告
if (props && hasOwn(props, key)) {
warn(
`Method "${key}" has already been defined as a prop.`,
vm
)
}
// 與保留字衝突警告
if ((key in vm) && isReserved(key)) {
warn(
`Method "${key}" conflicts with an existing Vue instance method. ` +
`Avoid defining component methods that start with _ or $.`
)
}
}
// 在實例上定義方法,賦值爲用戶未定義函數或空函數
vm[key] = methods[key] == null ? noop : bind(methods[key], vm)
}
}
複製代碼
initMethods
函數很是簡單,除了一大段在非生產環境裏報告檢查衝突的代碼,惟一的內容就是在實例上定義相應的方法而且把上下文綁定到實例對象上,這樣即使不是使用箭頭函數,在方法內也默認用 this 指代了實例對象。ide
// 定義initWatch函數,接受實例vm和配置屬性watch
function initWatch (vm: Component, watch: Object) {
// 遍歷watch
for (const key in watch) {
// 暫存屬性的值
const handler = watch[key]
// 若是handler是數組
if (Array.isArray(handler)) {
// 遍歷數組爲每個元素建立相應watcher
for (let i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i])
}
} else {
// 竇不然handler應該是函數,直接爲key建立watcher
createWatcher(vm, key, handler)
}
}
}
// 定義createWatcher函數
// 接受實例vm、表達式或函數expOrFn,處理器handler,可選的options
function createWatcher ( vm: Component, expOrFn: string | Function, handler: any, options?: Object ) {
// 若是handler是對象
if (isPlainObject(handler)) {
// 將handler賦值給options.
options = handler
// 從新賦值handler
handler = handler.handler
}
// 若是handler是字符串,在實例上尋找handler並賦值給handler
if (typeof handler === 'string') {
handler = vm[handler]
}
// 建立觀察並返回
return vm.$watch(expOrFn, handler, options)
}
複製代碼
initWatcher
爲傳入的觀察對象建立監視器,比較簡單。值得注意的是參數的傳入類型,觀察對象 expOrFn
能夠有兩種方式,一種是字符串,一種是函數,在 Watcher
類中對此參數進行了檢測,而在初始化的函數裏不對它作任何處理。handler
對象也能夠接受對象或字符串類型,在代碼中對這兩種傳入方式作判斷,最終找到handler引用的函數傳入 $watch
。
探索完了 initState
函數以後,繼續來看看 state
混入的方法 stateMixin
,在這個函數裏會提供上面還不曾提到的 $watch
方法的具體實現:
// 定義並導出stateMixin函數,接收參數Vue
export function stateMixin (Vue: Class<Component>) {
// 使用 Object.defineProperty 方法直接聲明定義對象時,flow會發生問題
// 因此必須在此程序化定義對象
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
// 定義dataDef對象
const dataDef = {}
// 定義dataDef的get方法,返回Vue實例私有屬性_data
dataDef.get = function () { return this._data }
// 定義propsDef對象
const propsDef = {}
// 定義propsDef的get方法,返回Vue實例私有屬性_props
propsDef.get = function () { return this._props }
// 非生產環境下,定義dataDef和propsDef的set方法
if (process.env.NODE_ENV !== 'production') {
// dataDef的set方法接收Object類型的newData形參
dataDef.set = function (newData: Object) {
// 提示避免傳入對象覆蓋屬性$data
// 推薦使用嵌套的數據屬性代替
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
)
}
// 設置propsDef的set方法爲只讀
propsDef.set = function () {
warn(`$props is readonly.`, this)
}
}
// 定義Vue原型對象公共屬性$data,並賦值爲dataDef
Object.defineProperty(Vue.prototype, '$data', dataDef)
// 定義Vue原型對象公共屬性$props,並賦值爲propsDef
Object.defineProperty(Vue.prototype, '$props', propsDef)
// 定義Vue原型對象的$set方法,並賦值爲從觀察者導入的set函數
Vue.prototype.$set = set
// 定義Vue原型對象的$delete方法,並賦值爲從觀察者導入的del函數
Vue.prototype.$delete = del
// 定義Vue原型對象的$watch方法
// 接收字符串或函數類型的expOrFn,從命名中可看出但願爲表達式或函數
// 接收任何類型的cb,這裏但願爲回調函數或者是一個對象
// 接收對象類型的options
// 要求返回函數類型
Vue.prototype.$watch = function ( expOrFn: string | Function, cb: any, options?: Object ): Function {
// 把實例賦值給vm變量,類型需爲Component
const vm: Component = this
// 若是cb是純粹的對象類型
if (isPlainObject(cb)) {
// 返回createWatcher函數
return createWatcher(vm, expOrFn, cb, options)
}
// 定義觀察目標的options,大多數狀況下爲undefined
options = options || {}
// 定義options的user屬性值爲true,標識爲用戶定義
options.user = true
// 建立watcher實例
const watcher = new Watcher(vm, expOrFn, cb, options)
// 若是options的immediate爲真
if (options.immediate) {
// 在vm上調用cb回調函數,並傳入watcher.value做爲參數
cb.call(vm, watcher.value)
}
// 返回unwatchFn函數
return function unwatchFn () {
// 執行watcher.teardown()方法清除觀察
watcher.teardown()
}
}
}
複製代碼
stateMixin執行的是關於狀態觀察的一系列方法的混入,主要是三個方面:
到這裏,關於狀態初始化的部分就探索完畢了,接下來要繼續研究另外一個與開發過程緊密關聯的部分——虛擬節點和模板渲染。
狀態初始化是與咱們在開發的時候最息息相關的部分,在建立實例對象的配置對象中,咱們設置了這些屬性和方法,實例初始化的過程當中對這些傳入的配置進行了不少預先的處理,這就是狀態初始化背後的邏輯。在探索到這一部分的時候才真正的感到,終於與平時的開發關聯起來了。