Adding Enter/Leave Transitions to Vue 3 Components
Owner: SnippetBot
Created: 2026-11-05 00:00:42
Size: 2.58 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<template>
<div class="transition-demo">
<button @click="show = !show">Toggle Element</button>
<h2>Basic Fade Transition</h2>
<!-- Basic Transition for v-if/v-show -->
<Transition name="fade">
<p v-if="show" class="transition-box">Hello, Vue 3 Transitions!</p>
</Transition>
<h2>Slide Transition with "appear"</h2>
<!-- Transition with initial render animation using `appear` prop -->
<Transition name="slide" appear>
<p v-if="show" class="transition-box">This element slides in and out.</p>
</Transition>
<h2>Custom Classes (e.g., Animate.css integration)</h2>
<!-- Using custom transition classes for more control or integrating third-party CSS libraries -->
<!-- Remember to install and import Animate.css: `npm install animate.css --save` -->
<!-- In main.js or App.vue: `import 'animate.css/animate.min.css';` -->
<Transition
name="custom-bounce"
enter-active-class="animate__animated animate__bounceIn"
leave-active-class="animate__animated animate__bounceOut"
>
<p v-if="show" class="transition-box">Animated with Animate.css!</p>
</Transition>
</div>
</template>
<script setup>
import { ref } from 'vue';
// If using Animate.css, ensure it's imported globally or in App.vue
// import 'animate.css/animate.min.css';
const show = ref(true);
</script>
<style>
/* Base styles for the demo */
.transition-demo {
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
max-width: 600px;
margin: 20px auto;
text-align: center;
}
.transition-box {
background-color: #e0f7fa;
border: 1px solid #00bcd4;
padding: 15px;
margin-top: 15px;
border-radius: 5px;
color: #006064;
font-weight: bold;
}
button {
background-color: #00bcd4;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
margin-bottom: 20px;
}
button:hover {
opacity: 0.9;
}
h2 {
margin-top: 25px;
color: #333;
}
/* 1. CSS for Basic Fade Transition */
/* State for entering element */
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s ease;
}
/* Starting point for enter, ending point for leave */
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
/* 2. CSS for Slide Transition */
.slide-enter-active, .slide-leave-active {
transition: all 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}
.slide-enter-from, .slide-leave-to {
transform: translateY(30px);
opacity: 0;
}
/* For Animate.css example, ensure animate.css is imported globally */
/* The classes animate__animated, animate__bounceIn, animate__bounceOut come from animate.css */
</style>