Introduction
Animations and transitions can significantly enhance the user experience by making UI elements feel more dynamic and interactive. In Vue 3, we can create reusable functionality to temporarily apply a CSS class to an element, allowing us to control animations easily.
In this article, we will learn how to:
Create a Vue 3 hook
useTemporaryClass
that temporarily applies a CSS class to an element to manage display transitions (fade in, fade out, etc.).Use this hook in a Vue 3 project with a practical example to show how it works in a dynamic list of books.
This approach makes it modular, reusable, and easy to integrate into any Vue application.
1. Creating the useTemporaryClass Hook
This custom hook helps add a CSS class to a DOM element and remove it automatically after a given duration. This is particularly useful for temporary animations like fading effects, highlight flashes, or alert dismissals.
📌 File: composables/useTemporaryClass.ts
import { ref, onUnmounted, nextTick } from 'vue'
export function useTemporaryClass(containerID, className, timeMs = 300) {
const container = ref(null)
const applyClass = async () => {
await nextTick()
container.value = document.getElementById(containerID)
if (container.value) {
container.value.classList.add(className)
setTimeout(() => {
container.value?.classList.remove(className)
}, timeMs)
}
}
applyClass()
onUnmounted(() => {
if (container.value) {
container.value.classList.remove(className)
container.value = null
}
})
return { container }
}
🔍 How It Works:
1 - The function receives:
containerID
: The ID of the element to modify.className
: The CSS class to be temporarily added.timeMs
: The duration (in milliseconds) before removing the class.
2 - It waits for the next DOM update (nextTick()
) to ensure the element exists.
3 - The class is added and removed after timeMs
milliseconds.
4 - When the component unmounts, it cleans up to avoid unwanted behavior.
2. Example: Applying Fade Effect to a Book List
Let’s apply this hook to a list of books, where clicking a button temporarily fades out an item before restoring it.
📌 Example Usage with a Book List (BookList.vue
)
<template>
<ul>
<li v-for="book in books" :key="book.id" :id="`book-${book.id}`">
{{ book.title }}
<button @click="toggleFade(book.id)">Fade</button>
</li>
</ul>
</template>
<script setup>
import { ref } from 'vue'
import { useTemporaryClass } from '@/composables/useTemporaryClass.js'
const books = ref([
{ id: 1, title: 'Harry Potter' },
{ id: 2, title: 'The Lord of the Rings' },
{ id: 3, title: 'Game of Thrones' },
])
function toggleFade(bookId) {
useTemporaryClass(`book-${bookId}`, 'fade', 1000)
}
</script>
<style scoped>
li {
transition: opacity 0.5s ease;
opacity: 1;
}
.fade {
opacity: 0;
}
</style>
📝 Explanation:
Each
<li>
item has an ID (e.g.,book-1
,book-2
).When clicking “Fade,” we call
useTemporaryClass
, applying the class.fade
for 1 second.The CSS rules handle the smooth fading effect.
After
1000ms
, the class is removed, bringing the book back to full opacity.
3. Why Use This Approach?
✅ Reusable & Modular: The useTemporaryClass
hook can be used in multiple components without repetition.
✅ Encapsulated Logic: Instead of handling timeouts manually in each component, the hook abstracts the complexity.
✅ Better Performance: Vue’s onUnmounted()
prevents unwanted class retention after a component is destroyed.
Conclusion
By combining Vue 3’s Composition API and CSS transitions, we have built a simple yet powerful temporary class hook. It allows you to enhance UX animations, such as fading elements, highlighting changes, or adding alert effects.
This hook is highly flexible and can be used beyond fading effects—consider animations for notifications, button clicks, or form validation messages.
With this implementation, you now have a solid tool to improve the interactivity of your Vue 3 projects! 🚀
Top comments (0)