onMounted
钩子函数:
- 调用时机:在组件挂载到DOM后调用,此时组件的模板已经被渲染到DOM中,可以安全地访问和操作DOM元素。
- 示例:
<template>
<div id="app-box"></div>
</template>
<script setup>
import { onMounted } from 'vue';
onMounted(() => {
const appBox = document.getElementById('app - box');
if (appBox) {
appBox.classList.add('active');
}
});
</script>
<style scoped>
.active {
background - color: lightblue;
}
</style>
onUnmounted
钩子函数:
- 调用时机:在组件从DOM中卸载后调用,即当组件被销毁时触发。
- 示例:
<template>
<div id="app-box"></div>
</template>
<script setup>
import { onMounted, onUnmounted } from 'vue';
onMounted(() => {
const appBox = document.getElementById('app - box');
if (appBox) {
appBox.classList.add('active');
}
});
onUnmounted(() => {
const appBox = document.getElementById('app - box');
if (appBox) {
appBox.classList.remove('active');
}
});
</script>
<style scoped>
.active {
background - color: lightblue;
}
</style>