1. Introduction
2. Step-by-Step Guide
Vue Transition Group is a component that allows you to manage a list of elements that can be animated as they enter, leave, or move within the list.
A Vue Transition Group wraps multiple items (for instance, in a list) and applies an animation/transition as they enter, leave, or move in the DOM. It tracks items in the list using their key
attribute.
To create transitions, you can use CSS classes that Vue Transition Group provides. These classes are applied during different stages of the transition:
v-enter
: Applied during the entire entering phase.v-enter-active
: Applied from start to end of entering phase.v-enter-to
: Applied only at the end of entering phase.Similar classes exist for the leave phase: v-leave
, v-leave-active
, and v-leave-to
.
3. Code Examples
<template>
<div>
<button @click="add">Add</button>
<button @click="remove">Remove</button>
<transition-group name="list" tag="p">
<span v-for="item in items" :key="item" class="list-item">
{{ item }}
</span>
</transition-group>
</div>
</template>
<script>
export default {
data() {
return {
items: [1, 2, 3, 4, 5]
};
},
methods: {
add() {
this.items.push(this.items.length + 1);
},
remove() {
this.items.shift();
}
}
};
</script>
<!-- CSS for transitions -->
<style scoped>
.list-item {
display: inline-block;
margin-right: 10px;
}
.list-enter-active, .list-leave-active {
transition: all 1s;
}
.list-enter, .list-leave-to {
opacity: 0;
transform: translateY(30px);
}
</style>
In the above example, transition-group
is wrapping multiple span
elements. Each span
represents an item in the list. The name
attribute in transition-group
is used to form the CSS classes for the transitions.
4. Summary
key
attribute in the children of transition-group
to track them.Next steps for learning could be exploring more complex animations and how to combine Vue Transition Group with Vue Router for page transitions.
5. Practice Exercises
Solutions
For the first exercise, you can use v-enter
and v-leave-active
to control the opacity during the enter and leave transitions.
For the sliding effect, you can use transforms in the v-enter
and v-leave-to
classes.
For the moving items, you can use the v-move
class which is applied automatically during list reordering.
These exercises will help you get practical experience with Vue Transition Group and understand how to control list transitions effectively. Happy coding!