Vue Transitions and Animations
Vue provides two built-in components, <Transition> and <TransitionGroup>, that help us easily add transition and animation effects to elements that are entering, leaving, or changing in lists.
The <Transition> Component
<Transition> is a built-in component, which means it can be used in any component's template without registration. It can apply animations to the entering and leaving of an element or component.
It supports scenarios including:
- Conditional rendering triggered by
v-iforv-show. - Dynamic components switched by
<component>. - Route transitions.
Usage
Simply wrap the elements that need transition effects with the <Transition> component.
When the <p> element is inserted or removed, Vue will automatically add or remove a series of CSS classes.
- Enter:
fade-enter-from: The starting state of the enter animation.fade-enter-active: Applied during the entire enter animation period.fade-enter-to: The ending state of the enter animation.
- Leave:
fade-leave-from: The starting state of the leave animation.fade-leave-active: Applied during the entire leave animation period.fade-leave-to: The ending state of the leave animation.
Here, fade is the name prop of the <Transition> component. If there's no name, the class prefix defaults to v.
The <TransitionGroup> Component
<TransitionGroup> is a component for adding transition effects to elements or components in a v-for list. It has several characteristics:
- By default, it doesn't render a wrapper element. But you can specify an element to render via the
tagprop. - Transition effects are applied to each internal element, not the container itself.
- You must provide a unique
keyattribute for each element in the list. - It can handle not only the entering and leaving of elements but also the movement of elements, which is achieved through the
v-moveclass.
Example: List Move Transition
The v-move class is applied when an element changes position. It's typically used to specify a CSS transition, making the list reordering process smooth.