Night picture with light effects.

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.

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:

  1. Conditional rendering via v-if
  2. Conditional display via v-show
  3. Dynamic components toggling via the <component> special element
  4. 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:

1
2
3
4
<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:

1
2
3
4
5
6
<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:

1
2
3
4
5
<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:

1
2
3
4
5
<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:

1
2
3
4
5
<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.

Credits: the header image is from Federico Beccari on Unsplash.

License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy