How to create reusable transitions in Vue
Duplicating animation code across multiple components leads to inconsistent user experiences and harder maintenance when you need to update animation timings or effects. As the creator of CoreUI with over 12 years of Vue.js experience since 2014, I’ve built reusable animation systems for numerous production applications. Vue allows you to create reusable transition components by wrapping the built-in Transition component and defining preset CSS classes. This approach centralizes your animation logic and ensures consistent motion design throughout your application.
Create a custom transition component that wraps Vue’s Transition with predefined animation styles.
<!-- FadeTransition.vue -->
<template>
<Transition name='fade' :mode='mode'>
<slot></slot>
</Transition>
</template>
<script setup>
defineProps({
mode: {
type: String,
default: 'out-in'
}
})
</script>
<style scoped>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
Use it in any component:
<template>
<button @click='show = !show'>Toggle</button>
<FadeTransition>
<p v-if='show'>This content fades in and out</p>
</FadeTransition>
</template>
<script setup>
import { ref } from 'vue'
import FadeTransition from './FadeTransition.vue'
const show = ref(true)
</script>
Best Practice Note
Create a library of reusable transitions like SlideTransition, ScaleTransition, and BounceTransition for different animation effects. Accept props for duration, easing, and mode to make transitions more flexible. You can also use JavaScript hooks (@before-enter, @enter, @after-enter) for more complex animations. This is exactly how we structure animations in CoreUI for Vue—providing consistent, reusable transition components that maintain design system coherence across all UI interactions.



