什么是生命周期
Vue中每个组件都是独立的,每个组件都有一个属于它的生命周期,从一个组件创建、数据初始化、挂载、更新、销毁、这就是一个组件所谓的生命中周期
Vue2.x中的生命周期
beforeCreate created beforeMount mounted beforeUpdate updated beforeDestroy destroyed activated deactivated errorCaptured
在Vue3.x中,新增了一个setup生命周期函数,setup执行的时机是在beforeCreate生命函数之前执行,因为在这个函数中不能通过this来获取实例的;同时为了命名的统一,将beforeDestory改名为beforeUnmount,destoryed改名为unmounted
beforeCreate(建议使用setup代替)created(建议使用setup代替) setup beforeMount mounted beforeUpdate updated beforeUnmount unmounted
vue3新增了生命周期钩子,我们可以通过在生命周期函数前加on来访问组件的生命周期
Composition API 形式的生命周期钩子
onBeforeMount onMounted
onBeforeUpdate onUpdated
onBeforeUnmount onUnmounted
onErrorCaptured
onRenderTracked
onRenderTriggered
- <script>
- import {
- onBeforeMount,
- onMounted,
- onBeforeUpdate,
- onUpdated,
- onBeforeUnmount,
- onUnmounted,
- ref
- } from 'vue'
-
- export default {
- setup () {
- // 其他的生命周期
- onBeforeMount (() => {
- console.log("App ===> 相当于 vue2.x 中 beforeMount")
- })
- onMounted (() => {
- console.log("App ===> 相当于 vue2.x 中 mounted")
- })
-
- // 注意,onBeforeUpdate 和 onUpdated 里面不要修改值
- onBeforeUpdate (() => {
- console.log("App ===> 相当于 vue2.x 中 beforeUpdate")
- })
-
- onUpdated (() => {
- console.log("App ===> 相当于 vue2.x 中 updated")
- })
-
- onBeforeUnmount (() => {
- console.log("App ===> 相当于 vue2.x 中 beforeDestroy")
- })
-
- onUnmounted (() => {
- console.log("App ===> 相当于 vue2.x 中 destroyed")
- })
-
- return {
- }
-
- }
- }
- script>