這一節主要記錄一下:Vue
的初始化過程html
如下正式開始:vue
Vue官網的生命週期圖示表數組
重點說一下 new Vue()
後的初始化階段,也就是created
以前發生了什麼。瀏覽器
initLifecycle
階段緩存
export function initLifecycle (vm: Component) {
const options = vm.$options
// locate first non-abstract parent
let parent = options.parent
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent
}
parent.$children.push(vm) // 本身把本身添加到父級的$children數組中
}
vm.$parent = parent // 父組件實例
vm.$root = parent ? parent.$root : vm // 根組件 若是不存在父組件,則自己就是根組件
vm.$children = [] // 用來存放子組件
vm.$refs = {}
vm._watcher = null
vm._inactive = null
vm._directInactive = false
vm._isMounted = false
vm._isDestroyed = false
vm._isBeingDestroyed = false
}
複製代碼
接下來是initEvents
階段服務器
// v-on若是寫在平臺標籤上如:div,則會將v-on上註冊的事件註冊到瀏覽器事件中
// v-on若是寫在組件標籤上,則會將v-on註冊的事件註冊到子組件的事件系統
// 子組件(Vue實例)在初始化的時候,有可能接收到父組件向子組件註冊的事件。
// 子組件(Vue實例)自身模板註冊的事件,只要在渲染的時候纔會根據虛擬DOM的對比結果
// 來肯定是註冊事件仍是解綁事件
// 這裏初始化的事件是指父組件在模板中使用v-on註冊的事件添加到子組件的事件系統也就是vue的事件系統。
export function initEvents (vm: Component) {
vm._events = Object.create(null) // 初始化
vm._hasHookEvent = false
// init parent attached events 初初始化腹肌組件添加的事件
const listeners = vm.$options._parentListeners
if (listeners) {
updateComponentListeners(vm, listeners)
}
}
export function updateComponentListeners ( vm: Component, listeners: Object, oldListeners: ?Object ) {
target = vm
updateListeners(listeners, oldListeners || {}, add, remove, createOnceHandler, vm)
target = undefined
}
複製代碼
initjections
階段ide
export function initInjections (vm: Component) {
// 自下而上讀取inject
const result = resolveInject(vm.$options.inject, vm)
if (result) {
// 設置爲false 避免defineReactive函數把數據轉換爲響應式
toggleObserving(false)
Object.keys(result).forEach(key => {
defineReactive(vm, key, result[key])
})
// 再次更改回來
toggleObserving(true)
}
}
export function resolveInject (inject: any, vm: Component): ?Object {
if (inject) {
// inject is :any because flow is not smart enough to figure out cached
const result = Object.create(null)
// 若是瀏覽器支持Symbol,則使用Reflect.ownkyes(),不然使用Object.keys()
const keys = hasSymbol
? Reflect.ownKeys(inject)
: Object.keys(inject)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
// #6574 in case the inject object is observed...
if (key === '__ob__') continue
const provideKey = inject[key].from
let source = vm
// 當provided注入內容的時候就是把內容注入到當前實例的_provided中
// 剛開始的時候 source就是實自己,擋在source._provided中找不到對應的值
// 就會把source設置爲父實例
// Vue實例化的第一步就是規格化用戶傳入的數據,因此inject無論時數組仍是對象
// 最後都會變成對象
while (source) {
if (source._provided && hasOwn(source._provided, provideKey)) {
result[key] = source._provided[provideKey]
break
}
source = source.$parent
}
// 處理默認值的狀況
if (!source) {
if ('default' in inject[key]) {
const provideDefault = inject[key].default
result[key] = typeof provideDefault === 'function'
? provideDefault.call(vm)
: provideDefault
} else if (process.env.NODE_ENV !== 'production') {
warn(`Injection "${key}" not found`, vm)
}
}
}
return result
}
}
複製代碼
initState
階段函數
在 Vue 中,咱們常常會用到 props 、methods 、 watch 、computed 、data 。這些狀態在使用前都須要初始化。而初始化的過程正是在 initState
階段完成。oop
由於 injects
是在 initState
以前完成,因此能夠在 State 中使用 injects 。ui
export function initState (vm: Component) {
vm._watchers = []
// 獲取到通過初始化的用戶傳進來的options
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) {
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
複製代碼
initProps
function initProps (vm: Component, propsOptions: Object) {
const propsData = vm.$options.propsData || {}
const props = vm._props = {}
// cache prop keys so that future props updates can iterate using Array
// instead of dynamic object key enumeration.
// 緩存props的key值
const keys = vm.$options._propKeys = []
const isRoot = !vm.$parent
// root instance props should be converted
// 若是不是跟組件則不必轉換成響應式數據
if (!isRoot) {
// 控制是否轉換成響應式數據
toggleObserving(false)
}
for (const key in propsOptions) {
keys.push(key)
// 獲取props的值
const value = validateProp(key, propsOptions, propsData, vm)
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.
// 把props代理到Vue實例上來,能夠直接經過this.props訪問
if (!(key in vm)) {
proxy(vm, `_props`, key)
}
}
toggleObserving(true)
}
複製代碼
initMethods
function initMethods (vm: Component, methods: Object) {
const props = vm.$options.props
for (const key in methods) {
if (process.env.NODE_ENV !== 'production') {
// 若是key不是一個函數 報錯
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
)
}
// isReserved判斷是否以$或_開頭
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的方法綁定到Vue實例上
vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)
}
}
複製代碼
initData
function initData (vm: Component) {
let data = vm.$options.data
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
// isPlainObject監測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
const keys = Object.keys(data)
const props = vm.$options.props
const methods = vm.$options.methods
let i = keys.length
// 循環data
while (i--) {
const key = keys[i]
if (process.env.NODE_ENV !== 'production') {
// 若是在methods中存在和key同名的屬性 則報錯
if (methods && hasOwn(methods, key)) {
warn(
`Method "${key}" has already been defined as a data property.`,
vm
)
}
}
// 若是在props中存在和key同名的屬性 則報錯
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)) {
// isReserved判斷是否以$或_開頭
// 代理data,使得能夠直接經過this.key訪問this._data.key
proxy(vm, `_data`, key)
}
}
// observe data
// 把data轉換爲響應式數據
observe(data, true /* asRootData */)
}
複製代碼
initComputed
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
// 判斷是否是服務端渲染
const isSSR = isServerRendering()
for (const key in computed) {
const userDef = computed[key]
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
)
}
// 若是不是ssr,則建立Watcher實例
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.
// 若是vm不存在key的同名屬性
if (!(key in vm)) {
defineComputed(vm, key, userDef)
} 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)
}
}
}
}
sharedPropertyDefinition = {
enumerable: true,
cnfigurable: true,
get: noop,
set: noop
}
export function defineComputed ( target: any, key: string, userDef: Object | Function ) {
// 若是是服務端渲染,則computed不會有緩存,由於數據響應式的過程在服務器是多餘的
const shouldCache = !isServerRendering()
// createComputedGetter返回計算屬性的getter
// createGetterInvoker返回userDef的getter
if (typeof userDef === 'function') {
sharedPropertyDefinition.get = shouldCache
? createComputedGetter(key)
: createGetterInvoker(userDef)
sharedPropertyDefinition.set = noop
} else {
// 當userDef爲一個對象時
sharedPropertyDefinition.get = userDef.get
? shouldCache && userDef.cache !== false
? createComputedGetter(key)
: createGetterInvoker(userDef.get)
: noop
sharedPropertyDefinition.set = userDef.set || noop
}
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
)
}
}
// 在tearget上定義一個屬性, 屬性名爲key, 屬性描述符爲sharedPropertyDefinition
Object.defineProperty(target, key, sharedPropertyDefinition)
}
function createComputedGetter (key) {
return function computedGetter () {
// 查找是否存在key的Watcher
const watcher = this._computedWatchers && this._computedWatchers[key]
if (watcher) {
// 若是dirty爲true,則從新計算,不然返回緩存
if (watcher.dirty) {
watcher.evaluate()
}
if (Dep.target) {
watcher.depend()
}
return watcher.value
}
}
}
function createGetterInvoker(fn) {
return function computedGetter () {
return fn.call(this, this)
}
}
複製代碼
initWatch
function initWatch (vm: Component, watch: Object) {
for (const key in watch) {
const handler = watch[key]
// 處理數組類型
if (Array.isArray(handler)) {
for (let i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i])
}
} else {
createWatcher(vm, key, handler)
}
}
}
function createWatcher ( vm: Component, expOrFn: string | Function, handler: any, options?: Object ) {
// isPlainObject檢查是不是對象
if (isPlainObject(handler)) {
options = handler
handler = handler.handler
}
if (typeof handler === 'string') {
handler = vm[handler]
}
// 最後調用$watch
return vm.$watch(expOrFn, handler, options)
}
複製代碼
initProvide
階段
export function initProvide (vm: Component) {
const provide = vm.$options.provide
if (provide) {
// 把provided存到_provided上
vm._provided = typeof provide === 'function'
? provide.call(vm)
: provide
}
}
複製代碼
到這裏 Vue
的初始化就結束了,接下來就是觸發生命週期函數 created
。
總結一下:new Vue()
執行以後,Vue
進入初始化階段。
初始化流程以下:
$options
,也就是用戶自定義的數據initLifecycle
注入生命週期initEvents
初始化事件,注意:這裏的事件是值在父組件在子組件上定義的事件initRender
initjections
初始化 jetction
initProps
初始化propsinitState
包括props
、methods
、data
、computed
、watch
initProvided
初始化 provide