文章目錄
- 前言
- 一、甚麼是[Vue的生命周期]?
- 二、生命周期函式
- 1.beforeCreate
- 2.created
- 3.beforeMount
- 4.mounted
- 5.beforeDestory
- 6.destoryed
- 7.beforeUpdate
- 8.updated
- 三、Vue的一生要做些甚麼?
- 1.Vue物件創立,Vue出生,
- 2.初始化
- 2.5BeforeCreated函式呼叫
- 3.繼續初始化
- 3.5Create函式呼叫
- 4.判斷el是否掛載了DOM
- 5.判斷是否有模板
- 5.5beforeMount函式呼叫
- 5.6前面生成的render函式被呼叫
- 6.虛擬el創建,DOM替換
- 6.5.DOM樹渲染至頁面完畢
- 7.Mounted函式呼叫,
- 8.準備完畢Mounted狀態
- 9.Vue實體被請求銷毀
- 9.5BeforeDestory函式呼叫
- 10.清除各Vue組件
- 11.組件銷毀完畢
- 12.Destory函式呼叫
- 總結
前言
升學,找作業,失業,找作業,買房,成家,一些人甚至至死都沒能跑完這條人生的長路,他們的一生在奔波中度過,卻不曾看到過一絲沿途的風景,
Vue是一個這樣的人,在他短暫而被安排的明明白白的人生路途中,只剩下奔波,沿途的風景未能讓他駐足一瞬,他創造的諸多美好,卻從無法看哪怕是一眼, 狗頭)
一、甚麼是[Vue的生命周期]?
Vue的每個組件都是獨立的,正因如此,Vue的每個組件也都有各自的生命周期(就像人的肺和腎都有自己的壽命),他們共同組成了[Vue的生命周期],
Vue并不像人的生命周期一樣有生老病死,如果Vue物件不被銷毀,Vue會一直在那里,所以“生命周期”這個詞在此處大可不必完全解讀為“生命周期”原本的意思,知道是Vue創立后固定要做的那么些事兒就好了,
二、生命周期函式
有時我們需要在Vue執行到某一步時,執行某些操作,那么可以利用這些生命周期函式來完成,把要執行的命令寫進這些生命周期函式里,在Vue執行到這些函式的所在時,就會順帶完成你需要的操作,而我們首先要知道這些周期函式在什么時候會被執行、他們都是哪些,
1.beforeCreate
在示例初始化、data observer配置和事件配置完成之間呼叫
2.created
初始化依賴和注入,data初始化完畢,計算屬性和event/watch事件進行回呼后,DOM樹掛載前,
通常會在此處進行一部分網路請求,
3.beforeMount
掛載前,創建虛擬el前,生成模板template后,
4.mounted
掛載完成,DOM樹渲染完畢后,
5.beforeDestory
Vue實體銷毀前,
6.destoryed
Vue所有子組件銷毀后,
7.beforeUpdate
資料data有更新,已被呼叫后,
8.updated
虛擬DOM重新渲染發生變化的資料,
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
const vm: Component = this
const prevEl = vm.$el
const prevVnode = vm._vnode
const restoreActiveInstance = setActiveInstance(vm)
vm._vnode = vnode
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode)
}
restoreActiveInstance()
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null
}
if (vm.$el) {
vm.$el.__vue__ = vm
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el
}
// updated hook is called by the scheduler to ensure that children are
// updated in a parent's updated hook.
}
三、Vue的一生要做些甚麼?
1.Vue物件創立,Vue出生,
建構式生成Vue實體;
new Vue();
2.初始化
原步驟Init Event&Lifecycle;
初始化事件相關:Event;
初始化各生命周期函式:Lifecycle(也叫鉤子函式);
import { initEvents } from './events'
import { mark, measure } from '../util/perf'
import { initLifecycle, callHook } from './lifecycle'
//src/core/instance/lifecycle.js
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)
}
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
}
以上為對生命周期函式lifecycle的初始化
//src/coreinstance/event.js
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)
}
}
以上為對事件Event的初始化
export function callHook(vm: Component, hook: string) {
// #7573 disable dep collection when invoking lifecycle hooks
pushTarget()
const handlers = vm.$options[hook]
const info = `${hook} hook`
if (handlers) {
for (let i = 0, j = handlers.length; i < j; i++) {
invokeWithErrorHandling(handlers[i], vm, null, vm, info)
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook)
}
popTarget()
}
以上為呼叫鉤子函式Hook
2.5BeforeCreated函式呼叫
生命周期函式BeforeCreated被呼叫,
//src/core/instance/init.js
callHook(vm, 'beforeCreate')
3.繼續初始化
原步驟Init injections & reactivity & state
初始化依賴提供:provide;
初始化依賴注入:injections;
初始化Vue回應式的核心:reactivity ;
provide提供依賴,提供的依賴可以是一個物件,或者是一個能回傳物件的函式,依賴內包含了屬性和屬性值,屬性值可以是一個物件,
injections 注入依賴,在后代組件里使用 inject 選項來為其注入需要添加在這個實體上的屬性,包含from和default默認值,
reactivity系列是Vue回應式的核心,

需要呼叫以上函式
//src/core/instance/inject.js
export function initProvide (vm: Component) {
const provide = vm.$options.provide
if (provide) {
vm._provided = typeof provide === 'function'
? provide.call(vm)
: provide
}
}
export function initInjections (vm: Component) {
const result = resolveInject(vm.$options.inject, vm)
if (result) {
toggleObserving(false)
Object.keys(result).forEach(key => {
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
defineReactive(vm, key, result[key], () => {
warn(
`Avoid mutating an injected value directly since the changes will be ` +
`overwritten whenever the provided component re-renders. ` +
`injection being mutated: "${key}"`,
vm
)
})
} else {
defineReactive(vm, key, result[key])
}
})
toggleObserving(true)
}
}
以上為初始化依賴提供provide與依賴注入injections
//src/core/instance/state.js
export function initState (vm: Component) {
vm._watchers = []
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)
}
}
以上為初始化state
3.5Create函式呼叫
生命周期函式Create被呼叫,

此段出自Vue原始碼檔案"init.js"
4.判斷el是否掛載了DOM
沒有掛載就掛載一個,
有就直接下一步,
watch事件回呼
this._init末的$mount函式運作,
//src/platform/web/runtime/index.js
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
return mountComponent(this, el, hydrating)
}
以上為$mount函式的基本模型
//src/platform/web/entry-runtime-with-compiler.js
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && query(el)
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
`Do not mount Vue to <html> or <body> - mount to normal elements instead.`
)
return this
}
以上為Vue中的$mount函式被呼叫
Vue.prototype.$watch = function (
expOrFn: string | Function,
cb: any,
options?: Object
): Function {
const vm: Component = this
if (isPlainObject(cb)) {
return createWatcher(vm, expOrFn, cb, options)
}
options = options || {}
options.user = true
const watcher = new Watcher(vm, expOrFn, cb, options)
if (options.immediate) {
try {
cb.call(vm, watcher.value)
} catch (error) {
handleError(error, vm, `callback for immediate watcher "${watcher.expression}"`)
}
}
return function unwatchFn () {
watcher.teardown()
}
}
$watch被呼叫
5.判斷是否有模板
模板template作為模板占位符,用來包裹HTML元素,其不會被渲染到頁面上,可以有三種寫法:作為option屬性寫在Vue物件里、直接作為HTML標簽、寫在script標簽里(第三個官方推薦寫法,為script標簽里的type屬性賦值"x-template"),
有template模板
把模板template轉換為render函式(render函式會在后續渲染DOM中發揮作用),
無template模板
將el掛載的物件的外層HTML作為模板template,
沒有物件就new一個啊(不是)
this._init末的$mount函式運作完畢,
//src/platform/web/entry-runtime-with-compiler.js
const options = this.$options
// resolve template/el and convert to render function
if (!options.render) {
let template = options.template
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template)
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !template) {
warn(
`Template element not found or is empty: ${options.template}`,
this
)
}
}
} else if (template.nodeType) {
template = template.innerHTML
} else {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this)
}
return this
}
} else if (el) {
template = getOuterHTML(el)
}
if (template) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile')
}
const { render, staticRenderFns } = compileToFunctions(template, {
outputSourceRange: process.env.NODE_ENV !== 'production',
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this)
options.render = render
options.staticRenderFns = staticRenderFns
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile end')
measure(`vue ${this._name} compile`, 'compile', 'compile end')
}
}
}
return mount.call(this, el, hydrating)
}
判斷是否具有模板template,若是無模板template就將外層HTML轉換為template;
5.5beforeMount函式呼叫
生命周期函式beforeMount被呼叫,
5.6前面生成的render函式被呼叫
render函式被呼叫來生成虛擬DOM,虛擬DOM是渲染好的,
Vue.prototype._render = function (): VNode {
const vm: Component = this
const { render, _parentVnode } = vm.$options
if (_parentVnode) {
vm.$scopedSlots = normalizeScopedSlots(
_parentVnode.data.scopedSlots,
vm.$slots
)
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentVnode
// render self
let vnode
try {
vnode = render.call(vm._renderProxy, vm.$createElement)
} catch (e) {
handleError(e, vm, `render`)
// return error render result,
// or previous vnode to prevent render error causing blank component
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production' && vm.$options.renderError) {
try {
vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e)
} catch (e) {
handleError(e, vm, `renderError`)
vnode = vm._vnode
}
} else {
vnode = vm._vnode
}
}
// if the returned array contains only a single node, allow it
if (Array.isArray(vnode) && vnode.length === 1) {
vnode = vnode[0]
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
)
}
vnode = createEmptyVNode()
}
// set parent
vnode.parent = _parentVnode
return vnode
}
以上為對render函式的呼叫
6.虛擬el創建,DOM替換
原步驟Create vm $el and replace “el” with it.
Vue實體下的虛擬el創建,虛擬DOM替換原本的DOM,
-render方法在此處運作生成虛擬DOM物件,
6.5.DOM樹渲染至頁面完畢
虛擬DOM掛載完畢,DOM樹已經成功渲染至頁面,頁面已經具有樣式,可以進行正常DOM操作,
7.Mounted函式呼叫,
生命周期函式Mounted呼叫,
8.準備完畢Mounted狀態
如果在這個狀態出現了資料更新需要再次渲染來更新頁面:
生命周期函式BeforeUpdate呼叫;
虛擬DOM重新渲染,但僅以最小的DOM開支渲染發生變化的部分,其他部分復用,節省作業量,
9.Vue實體被請求銷毀
9.5BeforeDestory函式呼叫
生命周期函式BeforeDestory呼叫,
10.清除各Vue組件
清除watchers、child子組件、components和eventlistener事件監聽 等等…
Vue.prototype.$destroy = function () {
const vm: Component = this
if (vm._isBeingDestroyed) {
return
}
callHook(vm, 'beforeDestroy')
vm._isBeingDestroyed = true
// remove self from parent
const parent = vm.$parent
if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
remove(parent.$children, vm)
}
// teardown watchers
if (vm._watcher) {
vm._watcher.teardown()
}
let i = vm._watchers.length
while (i--) {
vm._watchers[i].teardown()
}
// remove reference from data ob
// frozen object may not have observer.
if (vm._data.__ob__) {
vm._data.__ob__.vmCount--
}
// call the last hook...
vm._isDestroyed = true
// invoke destroy hooks on current rendered tree
vm.__patch__(vm._vnode, null)
// fire destroyed hook
callHook(vm, 'destroyed')
// turn off all instance listeners.
vm.$off()
// remove __vue__ reference
if (vm.$el) {
vm.$el.__vue__ = null
}
// release circular reference (#6759)
if (vm.$vnode) {
vm.$vnode.parent = null
}
}
}
$destory清除實體里的方法
11.組件銷毀完畢
12.Destory函式呼叫
生命周期函式Destory呼叫,
至此Vue的一段生命周期便執行完成,它完成了它的使命,暫時,
總結
今天先告一段落…
終于考完試了!打算下面幾天都拿來肝文了!
已經加入一些Vue原始碼片段來展示各個生命周期函式:~),我依然在完善這篇文章,部分代碼尚未找到,所以后續還會有增加…
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/276637.html
標籤:其他
下一篇:Java8新特性筆記
