文章目录
1、 定义
1.1 官方流程图
说到生命周期函数不得不提到此幅图:
1.2 解释
- 主线如下:
new Vue() ---->Init Events & LifeCycle (beforeCreate)---->Init injections & reactivity (created)
---->compile template or el’s outerHTML (beforeMount)---->create vm.$vm(mounted)---->Mounted
- 复线,当页面生成之后,再次渲染时,比如双向数据绑定的值改变时:
Mounted (updated)----> Virtual DOM re-render and patch (beforeUpdate)----> Mounted
- 当页面卸载时:
(beforeDestory)---->Teardown watchers,child components and event listeners
---->Destroyed (destroyed)
2 示例
2.1 单组件各周期钩子函数运行顺序
- 当页面刷新(即创建)时:
beforeCreate---->created---->beforeMount---->mounted
- 当页面数据更新时:
beforeUpdate---->updated
- 当页面退出时,依次执行的周期函数是:
beforeDestroy---->destroyed
2.2 父子组件之间周期钩子函数的运行顺序
- 当页面创建时(father代表父组件,child代表子组件):
beforeCreate-father--->created-father---->beforeMount-father---->beforeCreate-child
---->created-child---->beforeMount-child---->mounted-child---->mounted-father
- 当页面数据更新时:
beforeUpdate-father---->beforeUpdate-child ---->updated-child---->updated-father
- 当页面退出时:
beforeDestroy-father----> beforeDestroy -child---->destroyed-child----> destroyed-father
3 另类:activated与deactivated
是独立于传统的生命周期函数之外,只有配合keep-alive组件才会触发此钩子函数。Keep-alive的官方解释:包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。当组件在 内被切换,它的 activated 和 deactivated 这两个生命周期钩子函数将会被对应执行。所以当组件在 内页面退出时不会调用beforeDestroy()和destroyed()而是调用deactivated(),当再次进入此页面时不再是重新创建页面,而是将之前在缓存中未被销毁的页面显示出来,所以仅仅调用activated()。
3.1 单组件各周期钩子函数运行顺序
- 当页面创建时:
beforeCreate---->create---->beforeMount---->mounted---->activated
- 当页面数据更新时:
beforeUpdate ----> updated
- 当页面退出时:
deactivated
- 当再次进入此页面时:
activated
3.2 父子组件之间周期钩子函数的运行顺序
- 当页面创建时(father代表父组件,child代表子组件):
beforeCreate-father---->create-father---->beforeMount-father---->beforeCreate-child
---->create-child---->beforeMount-child---->mounted-child---->mounted-father
---->activated-child ---->activated-father
- 当页面数据更新时:
beforeUpdate-father ----> beforeUpdate-child ----> updated-child ----> updated-father
- 当页面退出时:
deactivated-child---->deactivated-father
- 当再次进入此页面时:
activated-child---->activated-father
4 补充
- 注1:在周期函数里执行异步操作,并不会等待异步操作完成再执行下一个周期函数。
- 注2:以上updated与beforeUpdate都只有在页面数据更新时才会触发,当页面创建时是不会调用这两函数的。
- 最后如果想动手试试可以clone我的git项目自己运行试试