And why you might want to use them
Vue has exceptional support for animated transitions. It’s one of the biggest advantages that it has over React. Take full advantage of it with custom JS transitions!
I’ll illustrate a simple example, explain why you might want to use it, and go through the important aspects, with the assumption that you already have a basic understanding of Vue 3.
(Considering that I usually write about reverse-engineering how certain UI effects are done, this is comparatively generic and simple, but you have to walk before you can run! This will open up a world of possibilities, which I will illustrate in future posts.)
The Live Example
Check out the Code Sandbox I made of this in action. In particular, the transition is for a “Collapser” component that expands and collapses to display or hide content with a 300ms animation when you click the header.
The <transition /> Component
Everything related to animating the entry and exit of elements happens through Vue’s Transition component. The API for Transition for CSS transitions is extremely clean, and for many cases will be all you will need. The Vue team created an example of this.
Transition accepts two important event handlers. The
enter event handler triggers when an element is entering the DOM and the
leave event handler triggers when an element is about to leave the DOM.
Take a look at the file
/src/animations/slide.js in the Code Sandbox. The function
useSlide returns two functions that have the function definition that the
leave event handlers expect.
elis the element that is entering or exiting, of type
doneis the function to call when you are done animating the element.
The entire process goes like this:
- You create functions with the function signature
(el, done)and pass it into a
<transition />component into
- When direct children of the
<transition />are being added or removed from the DOM, Vue calls your functions, which alter
el, likely in a way that creates animation.
- Eventually your functions call
done(), at which point the UI is finalized until the next state change.
It’s as simple as that! In order to avoid being too wordy, I knowingly left out some explanations for the code, so I highly recommend looking at the Code Sandbox example or fork it and tinker with it. Hopefully this short writeup and my example will help new Vue enthusiasts take their UIs to the next level!