Using the transition component in Vue

CSS animation is a cool feature natively available since CSS 3 and beyond. But I never had the real opportunity to play with them. With Vue, it is supported with a special built-in component.

Jérémie Litzler
2 min read6 days ago
Credits: the header image is from Federico Beccari on Unsplash.

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:

<button @click="show = !show">Toggle</button>
<Transition>
<p v-if="show">hello</p>
</Transition>

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:

<Transition>
<li :key="`image-${currentImage.title}`">
<!-- this is a Scope slot -->
<slot :item="{ ...currentImage }"></slot>
</li>
</Transition>

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:

<router-link v-slot="{ Component }">
<transition name="slide">
<component :is="Component" :key="$route.path"></component>
</transition>
</router-link>

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:

<button @click="show = !show">Toggle</button>
<Transition>
<p v-if="show">hello</p>
<p>the world</p>
</Transition>

However, this doesn’t mean you can’t cycle through multiple elements like this example:

<Transition>
<button v-if="docState === 'saved'">Edit</button>
<button v-else-if="docState === 'edited'">Save</button>
<button v-else-if="docState === 'editing'">Cancel</button>
</Transition>

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.

Originally published on iamjeremie.me.

--

--

Jérémie Litzler

I am a software engineer, but not just that: I thrive to improve life around me through observation and awareness about my impact in my environment.