下面的是vue2和3的生命周期对比,
下面的两张图是官网的图示:
vue2生命周期 vue3生命周期
与 2.x 版本生命周期相对应的组合式 API
beforeCreate
-> 使用setup()
created
-> 使用setup()
beforeMount
->onBeforeMount
mounted
->onMounted
beforeUpdate
->onBeforeUpdate
updated
->onUpdated
beforeDestroy
->onBeforeUnmount
destroyed
->onUnmounted
errorCaptured
->onErrorCaptured
示例代码:
目录结构如下:
App.vue
<template>
<h2>App父级组件</h2>
<button @click="isShow=!isShow">切换显示</button>
<Child v-if="isShow"/>
</template>
<script lang="ts">
import Child from './components/Child.vue'
import { defineComponent, ref} from 'vue'
export default defineComponent({
name: 'App',
components: {
Child
},
setup(){
const isShow = ref(true)
return {
isShow
}
}
})
</script>
Child.vue
<template>
<div>Child子级组件</div>
<h4>msg:{{msg}}</h4>
<button @click="update">更新数据</button>
</template>
<script lang="ts">
import { defineComponent, ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'
export default defineComponent({
name: 'Child',
// vue2.x中的生命周期钩子
beforeCreate(){
console.log('2.x 中的 beforeCreate ')
},
created(){
console.log('2.x 中的 created ')
},
beforeMount(){
console.log('2.x 中的 beforeMount ')
},
mounted(){
console.log('2.x 中的 mounted ')
},
beforeUpdate(){
console.log('2.x 中的 beforeUpdate ')
},
updated(){
console.log('2.x 中的 updated ')
},
// vue2.x中的beforeDestroy和destroyed这两个生命周期已经在vue3中改名了,所以不能再使用
beforeUnmount(){ // 已被废弃
console.log('2.x 中的 beforeUnmount ')
},
unmounted(){
console.log('2.x 中的 unmounted ')
},
setup(){
console.log('3.x中的 setup ')
// 响应式的数据
const msg = ref('abc');
// 按钮点击事件的回调
const update = () => {
msg.value += '==='
}
onBeforeMount(() => {
console.log('3.x 中的 onBeforeMount')
})
onMounted(() => {
console.log('3.x 中的 onMounted')
})
onBeforeUpdate(() => {
console.log('3.x 中的 onBeforeUpdate')
})
onUpdated(() => {
console.log('3.x 中的 onUpdated')
})
onBeforeUnmount(() => {
console.log('3.x 中的 onBeforeUnmount')
})
onUnmounted(() => {
console.log('3.x 中的 onUnmounted')
})
return {
msg,
update
}
}
})
</script>
根据示例代码:
初始化项目运行
点击更新数据后:
点击切换展示:
对比可以发现 2.x和3.x运行的情况下是:
在运行情况下:3.x运行早于2.x
3.x的生命周期等在使用时都需要引入