| Options API | Composition API | 说明 |
|---|
| beforeCreate | setup() | 组件创建前 |
| created | setup() | 组件创建后 |
| beforeMount | onBeforeMount | 挂载前 |
| mounted | onMounted | 挂载后 |
| beforeUpdate | onBeforeUpdate | 更新前 |
| updated | onUpdated | 更新后 |
| beforeUnmount | onBeforeUnmount | 卸载前 |
| unmounted | onUnmounted | 卸载后 |
| errorCaptured | onErrorCaptured | 错误捕获 |
| renderTracked | onRenderTracked | 渲染追踪 |
| renderTriggered | onRenderTriggered | 渲染触发 |
| activated | onActivated | keep-alive 激活 |
| deactivated | onDeactivated | keep-alive 停用 |
<script setup>
import {
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,
onActivated,
onDeactivated,
onErrorCaptured
} from 'vue'
onBeforeMount(() => {
console.log('Before Mount')
})
onMounted(() => {
console.log('Mounted')
})
onBeforeUpdate(() => {
console.log('Before Update')
})
onUpdated(() => {
console.log('Updated')
})
onBeforeUnmount(() => {
console.log('Before Unmount')
})
onUnmounted(() => {
console.log('Unmounted')
})
onActivated(() => {
console.log('Activated')
})
onDeactivated(() => {
console.log('Deactivated')
})
onErrorCaptured((err, instance, info) => {
console.log('Error Captured', err)
return false
})
</script>
<script setup>
import { ref, onMounted } from 'vue'
const data = ref(null)
onMounted(async () => {
const response = await fetch('/api/data')
data.value = await response.json()
})
</script>
<script setup>
import { ref, onMounted } from 'vue'
const inputRef = ref(null)
onMounted(() => {
inputRef.value.focus()
})
</script>
<template>
<input ref="inputRef" />
</template>
<script setup>
import { onMounted, onUnmounted } from 'vue'
let timer
onMounted(() => {
timer = setInterval(() => {
console.log('tick')
}, 1000)
})
onUnmounted(() => {
if (timer) {
clearInterval(timer)
}
})
</script>
<script setup>
import { onMounted, onUnmounted } from 'vue'
const handleResize = () => {
console.log('window resized')
}
onMounted(() => {
window.addEventListener('resize', handleResize)
})
onUnmounted(() => {
window.removeEventListener('resize', handleResize)
})
</script>
父 setup
父 onBeforeMount
子 setup
子 onBeforeMount
子 onMounted
父 onMounted
父 onBeforeUpdate
子 onBeforeUpdate
子 onUpdated
父 onUpdated
父 onBeforeUnmount
子 onBeforeUnmount
子 onUnmounted
父 onUnmounted