vue3--生命周期

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

  • setup 函数会在 beforeCreate 之前调用,因为此时组件的 datamethods 还没有初始化,因此在 setup 中是不能使用 this 的。
  • 所以 Vue 为了避免我们错误的使用,它直接将 setup 函数中的 this 修改成了undefined
  • setup函数,只能是同步的不能是异步的
vue2vue3
beforeCreatesetup
createdsetup
beforeMountonBeforeMount
mountedonMounted
beforeUpdateonBeforeUpdate
updatedonUpdated
beforeDestroyonBeforeUnmount
destroyedonUnmounted
activatedonActivated
deactivatedonDeactivated
errorCapturedonErrorCaptured
- -onRenderTracked
- -onRenderTriggered
<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');
	},
  beforeMount(){
    console.log('beforeMount');
  },  
  mounted(){
    console.log("mounted");
  }
}

</script>

setup
beforeCreate
created
onBeforeMount
beforeMount
onMounted
mounted

加载顺序
setup => beforeCreate => created => onBeforeMount => beforeMount => onMounted => mounted

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值