Vue3.x 生命周期

Vue2.x 生命周期传送门


Vue2 和 Vue3 中的生命周期钩子函数非常相似,我们仍然可以在 Vue3 中使用 Vue2 的生命周期钩子函数。

但是,随着 Composition API 的引入,我们访问这些钩子函数的方式已经改变。

Vue3 Composition API 附带了一个 setup() 方法,此方法封装了我们的大多数组件代码,并处理了响应式,生命周期钩子函数等。使我们能够更好地将代码组织为更多的模块化功能,而不是根据属性的类型(方法,计算的数据)进行分离。

setup 函数是 Vue3 中新增的一个生命周期函数:

  • setup 函数会在 beforeCreate 之前调用,因为此时组件的 datamethods 还没有初始化,因此在 setup 中是不能使用 this
  • 所以 Vue 为了避免我们错误的使用,它直接将 setup 函数中的 this 修改成了undefined
  • setup函数,只能是同步的不能是异步
Vue2.xVue3.x
beforeCreatesetup
createdsetup
beforeMountonBeforeMount
mountedonMounted
beforeUpdateonBeforeUpdate
updatedonUpdated
beforeDestroyonBeforeUnmount
destroyedonUnmounted
activatedonActivated
deactivatedonDeactivated
errorCapturedonErrorCaptured
- -onRenderTracked
- -onRenderTriggered

初始化加载顺序:

setup => beforeCreate => created => onBeforeMount => onMounted

<script>
import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, onRenderTracked, onRenderTriggered } from 'vue'
export default {
	setup () {
		console.log('setup');
		
		// 生命周期钩子(没有beforeCreate和created)
		onBeforeMount(() => { console.log('onBeforeMount'); })
		onMounted(() => { console.log('onMounted'); })
		onBeforeUpdate(() => { console.log('onBeforeUpdate'); })
		onUpdated(() => { console.log('onUpdated'); })
		onBeforeUnmount(() => { console.log('onBeforeUnmount'); })
		onUnmounted(() => { console.log('onUnmounted'); })

		// 新增的debug钩子  生产环境中会被忽略
		onRenderTracked(() => { console.log('onRenderTracked'); }) // 每次渲染后重新收集响应式依赖,在onMounted前触发,页面更新后也会触发
		onRenderTriggered(() => { console.log('onRenderTriggered'); }) // 每次触发页面重新渲染时的自动执行,在onBeforeUpdate之前触发
	},
	beforeCreate () {
		console.log('beforeCreate');
	},
	created () {
		console.log('created');
	}
}
</script>
posted @ 2022-07-20 18:15  猫老板的豆  阅读(38)  评论(0编辑  收藏  举报