Until I took the Vue.js certification when it tested my understanding of the concept, I hadn’t understood it fully.
So how the Transition
and TransitionGroup
work?
The Use Cases
Well, if you read the documentation properly (take your time), you can understand easily:
The transition can be triggered by one of the following:
- Conditional rendering via
v-if
- Conditional display via
v-show
- Dynamic components toggling via the
<component>
special element- Changing the special
key
attribute
What does each use case mean
Use cases 1 and 2 are pretty similar: Let’s take this template, with v-if
:
|
|
When show
changes, Vue toggles the paragraph and runs the transition.
You can replace the v-if
with v-show
and you get the exact same thing.
What about use case 3? In the scenario of an image swipe, we could have this:
|
|
When you move from an image to another, the currentImage.title
updates and so does the :key
and it triggers the transition.
The use case 4 was the toughest to understand. It has to do with the <component>
special element that you can use alongside the Vue router. Here is an example:
|
|
Basically, the transition will run each time the route path changes.
Also, remember that <Transition>
only supports a single element or component as its slot content. If the content is a component, the component must also have only one single root element.
So this wouldn’t work:
|
|
However, this doesn’t mean you can’t cycle through multiple elements like this example:
|
|
Learn More
See the full code for this example in the SFC Playground.
There is more about using transitions, like Transition Modes, Transition Between Components or Dynamic Transitions, so feel free to check out the documentation.
Credits: the header image is from Federico Beccari on Unsplash.