前言 前面我們簡單的瞭解了 vue 初始化時的一些大概的流程,這裡我們詳細的瞭解下具體的內容; 內容 這一塊主要圍繞init.ts中的initState進行剖析,初始化生命周期之後緊接著。 initState initState的方法位於scr/core/instance/state.ts中; co ...
前言
前面我們簡單的瞭解了 vue 初始化時的一些大概的流程,這裡我們詳細的瞭解下具體的內容;
內容
這一塊主要圍繞init.ts
中的initState
進行剖析,初始化生命周期之後緊接著。
initState
initState
的方法位於scr/core/instance/state.ts
中;
const sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
}
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)
}
export function initState(vm: Component) {
const opts = vm.$options
// 存在props則初始化props
if (opts.props) initProps(vm, opts.props)
// Composition API
// 初始化組合式API
initSetup(vm)
// 存在方法則初始化方法
if (opts.methods) initMethods(vm, opts.methods)
// 存在data則初始化data
if (opts.data) {
initData(vm)
} else {
const ob = observe((vm._data = {}))
ob && ob.vmCount++
}
// 存在計算屬性則初始化計算屬性
if (opts.computed) initComputed(vm, opts.computed)
// 存在監聽且監聽不等於nativeWatch(這個主要是針對火狐瀏覽器進行處理)則初始化監聽
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
function initProps(vm: Component, propsOptions: Object) {
const propsData = vm.$options.propsData || {}
const props = (vm._props = shallowReactive({}))
// cache prop keys so that future props updates can iterate using Array
// instead of dynamic object key enumeration.
// 緩存prop的keys以便將來更新props時可以使用數組代替動態的迭代對象key
const keys: string[] = (vm.$options._propKeys = [])
// 判斷是否是根組件
const isRoot = !vm.$parent
// root instance props should be converted
if (!isRoot) {
// 如果不是根組件就關閉響應式處理,防止defineReactive做響應式處理
toggleObserving(false)
}
for (const key in propsOptions) {
keys.push(key)
// 對prop數據進行校驗
const value = validateProp(key, propsOptions, propsData, vm)
/* istanbul ignore else */
if (__DEV__) {
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 (!isRoot && !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)
}
// static props are already proxied on the component's prototype
// during Vue.extend(). We only need to proxy props defined at
// instantiation here.
// 在Vue.extend()過程中,靜態props已經在組件的原型上被代理。我們只需要在這裡實例化時代理定義的props。
if (!(key in vm)) {
proxy(vm, `_props`, key)
}
}
// 開啟響應式處理
toggleObserving(true)
}
/**
* 初始化data
* @param vm
*/
function initData(vm: Component) {
let data: any = vm.$options.data
// 通過getData將函數轉為對象
data = vm._data = isFunction(data) ? getData(data, vm) : data || {}
if (!isPlainObject(data)) {
data = {}
// https://v2.cn.vuejs.org/v2/guide/components.html#data-%E5%BF%85%E9%A1%BB%E6%98%AF%E4%B8%80%E4%B8%AA%E5%87%BD%E6%95%B0
// 一個組件的 data 選項必須是一個函數,因此每個實例可以維護一份被返回對象的獨立的拷貝
// 避免了實例之間相互影響
__DEV__ &&
warn(
'data functions should return an object:\n' +
'https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
)
}
// proxy data on instance
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]
// 檢查key名是否在methods中已經使用
if (__DEV__) {
if (methods && hasOwn(methods, key)) {
warn(`Method "${key}" has already been defined as a data property.`, vm)
}
}
// 檢查key名是否在props中使用
if (props && hasOwn(props, key)) {
__DEV__ &&
warn(
`The data property "${key}" is already declared as a prop. ` +
`Use prop default value instead.`,
vm
)
// 檢查key名是否符合規範,即不以$和_開頭
} else if (!isReserved(key)) {
// 代理數據 |本質上還是 Object.defineProperty
proxy(vm, `_data`, key)
}
}
// observe data | 響應式數據
const ob = observe(data)
ob && ob.vmCount++
}
/**
* 獲取data內容|轉為對象
* @param data
* @param vm
* @returns
*/
export function getData(data: Function, vm: Component): any {
// #7573 disable dep collection when invoking data getters
pushTarget()
try {
return data.call(vm, vm)
} catch (e: any) {
handleError(e, vm, `data()`)
return {}
} finally {
popTarget()
}
}
const computedWatcherOptions = { lazy: true }
function initComputed(vm: Component, computed: Object) {
// $flow-disable-line
// 創建一個空對象
const watchers = (vm._computedWatchers = Object.create(null))
// computed properties are just getters during SSR
// 計算的內容只是SSR期間的getter
// 是否服務端渲染
const isSSR = isServerRendering()
for (const key in computed) {
const userDef = computed[key]
const getter = isFunction(userDef) ? userDef : userDef.get
if (__DEV__ && getter == null) {
warn(`Getter is missing for computed property "${key}".`, vm)
}
if (!isSSR) {
// create internal watcher for the computed property.
// 不是服務端渲染,就為計算屬性創建內部觀察程式。
// noop 空函數:function() {}
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.
// 組件定義的計算內容已經在組件原型上定義。我們只需要在這裡定義實例化時定義的計算內容。
if (!(key in vm)) {
defineComputed(vm, key, userDef)
} else if (__DEV__) {
// 開發環境下檢查key名是否被過早的定義在data,props,methods中
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)
} else if (vm.$options.methods && key in vm.$options.methods) {
warn(
`The computed property "${key}" is already defined as a method.`,
vm
)
}
}
}
}
export function defineComputed(
target: any,
key: string,
userDef: Record<string, any> | (() => any)
) {
// 是否服務端渲染
const shouldCache = !isServerRendering()
// 定義get和set
if (isFunction(userDef)) {
sharedPropertyDefinition.get = shouldCache
? createComputedGetter(key)
: createGetterInvoker(userDef)
sharedPropertyDefinition.set = noop
} else {
sharedPropertyDefinition.get = userDef.get
? shouldCache && userDef.cache !== false
? createComputedGetter(key)
: createGetterInvoker(userDef.get)
: noop
sharedPropertyDefinition.set = userDef.set || noop
}
if (__DEV__ && sharedPropertyDefinition.set === noop) {
sharedPropertyDefinition.set = function () {
warn(
`Computed property "${key}" was assigned to but it has no setter.`,
this
)
}
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}
function createComputedGetter(key) {
return function computedGetter() {
const watcher = this._computedWatchers && this._computedWatchers[key]
if (watcher) {
// 是否被計算過,如果dirty為true表明未被計算過
if (watcher.dirty) {
watcher.evaluate() // 調用watcher.get方法,值會保存在watcher.value上
}
if (Dep.target) {
if (__DEV__ && Dep.target.onTrack) {
Dep.target.onTrack({
effect: Dep.target,
target: this,
type: TrackOpTypes.GET,
key
})
}
watcher.depend()
}
return watcher.value
}
}
}
function createGetterInvoker(fn) {
return function computedGetter() {
return fn.call(this, this)
}
}
function initMethods(vm: Component, methods: Object) {
const props = vm.$options.props
// 迴圈遍歷methods
for (const key in methods) {
if (__DEV__) {
// 不是函數類型發出警告
if (typeof methods[key] !== 'function') {
warn(
`Method "${key}" has type "${typeof methods[
key
]}" 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 $.`
)
}
}
// 將methods綁定在當前實例上
vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)
}
}
function initWatch(vm: Component, watch: Object) {
// 遍歷watch
for (const key in watch) {
const handler = watch[key]
// 是否是數組
if (isArray(handler)) {
// 迴圈創建watcher監聽回調函數
for (let i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i])
}
} else {
// 創建watcher監聽回調函數
createWatcher(vm, key, handler)
}
}
}
function createWatcher(
vm: Component,
expOrFn: string | (() => any),
handler: any,
options?: Object
) {
// 檢查是否是普通對象
if (isPlainObject(handler)) {
// 將handler掛載到options屬性上
options = handler
// 提取handler屬性賦值給handler
handler = handler.handler
}
// 是否是字元串
if (typeof handler === 'string') {
// 從實例中找到handler賦值給handler
handler = vm[handler]
}
// 實例上的$watch方法
return vm.$watch(expOrFn, handler, options)
}
學無止境,謙卑而行.