[TOC]
1. 版本对比
2. 配置项形式:
Vue3.0中可以继续使用Vue2.x中的生命周期钩子,但有有两个被更名:
- beforeDestroy改名为 beforeUnmount
- destroyed改名为 unmounted
```javascript
//parent
//child
count:{{count}}
初始化顺序为: setup => beforeCreate => created => beforeMount => mounted<br />更新:beforeUpdate => updated<br />卸载: beforeUnmount =>unmounted
<a name="EDowE"></a>
# 3. 组合式声明周期
可以直接已配置项的形式使用生命周期钩子,也可以使用组合式API的形式使用,尽量统一<br />一般来说,组合式API里的钩子会比配置项的钩子先执行,组合式API的钩子名字有变化
- Vue3.0也提供了 Composition API 形式的生命周期钩子,与Vue2.x中钩子对应关系如下:
- beforeCreate===>setup()
- created=======>setup()
- beforeMount ===>onBeforeMount
- mounted=======>onMounted
- beforeUpdate===>onBeforeUpdate
- updated =======>onUpdated
- beforeUnmount ==>onBeforeUnmount
- unmounted =====>onUnmounted
```javascript
<template>
<my-child v-if="isShow" />
<br />
<br />
<button @click="isShow = !isShow">显示/影藏</button>
</template>
<script>
import {
ref,
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,
} from 'vue'
import MyChild from './MyChild.vue'
export default {
components: { MyChild },
setup() {
console.log('setup')
const isShow = ref(true)
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 { isShow }
},
}
</script>
初始化: upset => onBeforeMount => onMounted
更新: onBeforeUpdate => onUpdated
卸载: onBbeforeUnmount =>onUnmounted
4. 总结
组合式api里面写的生命周期函数比配置项写的声明周期函数执行的快一些。
<template>
<h2>count:{{count}}</h2>
<button @click="count++">+</button>
</template>
<script>
import { ref ,onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,} from 'vue'
export default {
setup() {
console.log('setup')
const count = ref(0)
onBeforeMount(() => {
console.log('onBeforeMount')
})
onMounted(() => {
console.log('onMounted')
})
return { count }
},
beforeMount(){
console.log('beforeCreate')
},
mounted(){
console.log('created')
}
}
</script>