Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

简述 Vue 的生命周期以及每个阶段做的事 #107

Open
GGXXMM opened this issue Mar 4, 2022 · 0 comments
Open

简述 Vue 的生命周期以及每个阶段做的事 #107

GGXXMM opened this issue Mar 4, 2022 · 0 comments
Labels

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Mar 4, 2022

Vue的生命周期

Vue1 的生命周期比较简单,分为7个阶段:

生命周期vue1 描述
init 组件初始化
created 组件创建
beforeCompile 组件编译之前
compiled 组件编译之后
ready 组件准备
beforeDestroy 组件销毁前
destroyed 组件销毁完成

Vue2 的生命周期总共分为8个阶段:创建前后、载入前后、更新前后、销毁前后,以及一些特殊场景的生命周期。比如 Vue3 新增了调试和服务端渲染场景。

生命周期vue2 生命周期vue3 描述
beforeCreate setup 组件实例被创建之初
created setup 组件实例已经完全创建
beforeMount beforeMount 组件挂载之前
mounted onMounted 组件挂载到实例上去之后
beforeUpdate onBeforeUpdate 组件数据发生变化,更新之前
updated onUpdated 数据更新之后
beforeDestroy onBeforeUnmount 组件实例销毁之前
destroyed onUnmounted 组件实例销毁之后
activated activated keep-alive 缓存的组件激活时调用
deactivated deactivated keep-alive 缓存的组件停用时调用
errorCaptured errorCaptured 捕获一个来自子孙组件的错误时被调用
- renderTracked 调试钩子,响应式依赖被收集时调用
- renderTriggered 调试钩子,响应式依赖被触发时调用
- serverPrefetch ssr only,组件实例在服务器上被渲染前调用

image

生命周期结合实践

beforeCreate:通常用于插件开发中执行一些初始化任务
created:组件初始化完毕,可以访问各种数据,获取接口数据等
mounted:dom已创建,可用于获取访问数据和dom元素;访问子组件等
beforeUpdate:view层还未更新,可用于获取更新前各种状态
updated:完成view层的更新,可以用于获取更新后的状态
beforeUnmount:实例被销毁前调用,可用于一些定时器或订阅的取消
unmounted:销毁一个实例。可清理它与其他实例的连接,解绑它的全部指令及事件监听器

@GGXXMM GGXXMM added the vue label Mar 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant