Arms crossed picture of James Auble

A Quick Vue.js Transitions Demo

PublishedFeb 16th, 2022

In this quick tutorial we’re gonna take a quick look at how to implement Vue.js built-in transitions to smoothly style the way elements and components enter and leave your page. If you’re looking for a full run down of transitions I recommend you check out the official docs at https://vuejs.org/v2/guide/transitions.html.

To show how transitions can be used to spin and move an element on and off screen we can first start with very simple markup that has a button and a conditionally rendered div within our main app div:

<div id="app">
  <button @click="show = !show">Toggle</button>
  <br>
    <div style="display: inline-block;" v-show="show">Toggled Line</div>
</div>

and our javascript with our show variable:

new Vue({
  el: '#app',
  data: () => ({
    show: false
  })
})

So far we’re simply showing or hiding our div. To implement a transition, we’re first going wrap the element we want to transition in <transition> tags and name it.

<div id="app">
  <button @click="show = !show">Toggle</button>
  <br>
    <transition name="spinOut">
<div style="display: inline-block;" v-show="show">Toggled Line</div>
   </transition>
</div>

Make sure you add style=”display: inline-block” to the toggled div — it’ll be needed later.

When Vue.js detects the <transition> tag it will now going sniffing around in your css looking for the follow class rules:

<transition-name>-enter

<transition-name>-enter-active

<transition-name>-enter-to (only available in versions 2.1.8+)

<transition-name>-leave

<transition-name>-leave-active

<transition-name>-leave-to

So in our case Vue will be looking for .spinOut-enter {} etc… in our css. When detected, these classes will automatically be added to whatever your transition tag is wrapping.

Let’s now add some css classes to animate our toggled div on and off the screen:

.spinOut-enter-active, .slide-leave-active {
  transition: all 1s;
}
.spinOut-leave-to {
  transform: translateY(-100px) rotate(180deg);
}
.spinOut-enter {
  transform: translateY(-100px) rotate(180deg);
}
.spinOut-enter-to {
  transform: translateX(0), rotate(0deg);
}

That’s it! You should now see your div spin up and out of view when it leaves and spin down into place when it returns.

See it in action in my codepen: https://codepen.io/James0r/pen/gZNZrG .

To learn more about when exactly each transition class is added to your elements be sure to check out the official docs https://vuejs.org/v2/guide/transitions.html.

I hope you enjoyed this very brief tutorial and happy transitioning and animating!

Scrolldown Icon