[Vue3] Study Notes - Life Cycle

Vue2.x and vue3 life cycle

insert image description here

  • The lifecycle hooks in Vue2.x can continue to be used in Vue3.0, but two of them have been renamed:
    • beforeDestroyrename tobeforeUnmount
    • destroyedrename tounmounted
  • Vue3.0 also provides lifecycle hooks in the form of Composition API, and the corresponding relationship with the hooks in Vue2.x is as follows:
    • beforeCreate===>setup()
    • created=======>setup()
    • beforeMount ===>onBeforeMount
    • mounted=======>onMounted
    • beforeUpdate===>onBeforeUpdate
    • updated =======>onUpdated
    • beforeUnmount ==>onBeforeUnmount
    • unmounted =====>onUnmounted

Demo.vue

<template>
	<h2>当前求和为:{
    
    {
    
    sum}}</h2>
	<button @click="sum++">点我+1</button>
	<hr>
</template>

<script>
	import {
    
    ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted} from 'vue'
	export default {
    
    
		name: 'Demo',
		setup(){
    
    
			//数据
			let sum = ref(0)
            //通过组合API的形式使用生命周期钩子
			onBeforeMount(()=>{
    
    
				console.log('-----onBeforeMount------')
			})
			onMounted(()=>{
    
    
				console.log('-----onMounted------')
			})
			onBeforeUpdate(()=>{
    
    
				console.log('-----onBeforeUpdate------')
			})
			onUpdated(()=>{
    
    
				console.log('-----onUpdated------')
			})
			onBeforeUnmount(()=>{
    
    
				console.log('-----onBeforeUnmount------')
			})
			onUnmounted(()=>{
    
    
				console.log('-----onUnmounted------')
			})
			//返回一个对象(常用)
			return {
    
    
				sum
			}
		},
		//通过配置项的形式使用生命周期钩子
		//#region 
/* 		beforeCreate(){
			console.log('----beforeCreate------')
		},
		created(){
			console.log('----created------')
		},
		beforeMount(){
			console.log('----beforeMount------')
		},
		mounted(){
			console.log('----mounted------')
		},
		beforeUpdate(){
			console.log('----beforeUpdate------')
		},
		updated(){
			console.log('----updated------')
		},
		beforeUnmount(){
			console.log('----beforeUnmount------')
		},
		unmounted(){
			console.log('----unmounted------')
		} */
		//#endregion

	}
</script>


insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/david_520042/article/details/131471482