vue3有两种写法:类方式、函数方式
两种方式的生命周期也不一样:
类方式 | 函数方式(也称hooks方式) |
beforeCreate | setup |
created | setup |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeUnmount | onBeforeUnmount |
unmounted | onUnmounted |
类方式的生命周期用法和vue一样;
函数方式的生命周期用法:
- 生命周期要写在setup中
- 要导入生命周期
- 生命周期参数是一个回调函数
<script>
import {onMounted} from 'vue'
export default {
setup(){
...
onMounted(()=>{
console.log('onMounted')
})
...
}
}
</script>