vue3的生命周期钩子函数有2种写法
- 一种是写在配置项中
- 一种是写在 setup 函数内
写在配置项中的生命钩子函数
<template> <div>{{sum}}</div> <button @click="sum++">自增</button> </template> <script> import {ref, } from 'vue' export default { name: 'Demo', setup() { let sum = ref(1) return { sum, } }, 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('beforeUmount'); }, unmounted() { console.log('unmounted'); } } </script>
写在 setup 函数中的生命周期钩子函数
<template> <div>{{sum}}</div> <button @click="sum++">自增</button> </template> <script> import {ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted, } from 'vue' export default { name: 'Demo', setup() { // beforeCreated created 两个生命钩子函数被 setup 生命周期钩子函数所替换 console.log(`setup`); let sum = ref(1) // 使用组合式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, } }, } </script>
- setup 函数也算是生命周期钩子函数,用于替换以前配置项中的 beforeCreate 和 created 两个生命周期钩子函数