Integrate Motion with Vue 3
Motion is fully framework agnostic, therefore it works within any JavaScript environment, including Vue 3. In this guide, we'll learn how to:
Animate on enter and exit
Perform view/layout animations
Animate timeline sequences
Animate when props change
Change HTML and CSS when an element enters or leaves the viewport
Animate on scroll
Install
Install Motion into the Vue project.
Enter and exit animations
To animate elements when they enter and exit the DOM, we can use Vue's Transition
component.
Start by creating an onEnter
function with Motion's animate
function.
You can now provide this to Transition
with the @enter
event.
Likewise, to animate when a component exits, you can make a onLeave
function.
Then pass this to the @leave
event.
View animations
Motion's powerful view()
function (currently in Motion+ early access) can perform full page transitions, animate between different layouts and even between different elements.
By await
-ing Vue's nextTick
function within view
's update function, we ensure the view animation starts after the page has been updated.
Animate timeline sequences
onEnter
and onLeave
are passed the element provided as the first Transition
child, in this case the ul
:
This is useful for building timeline animations scoped to the component:
Animate on prop change
Using Vue's watch
function and refs, we can start watching changes in props passed into the component to trigger animate
calls.
Add a cleanup function to ensure animations are stopped when the component's removed.
Viewport detection
With Motion's inView
function, it's possible to detect when an element enters or leaves the viewport and change its appearance accordingly.
Start by adding a ref
to track visibility state:
We can attach a "container"
ref
to an element in our template:
We can now pass this element to inView
within an onMounted
lifecycle hook.
Finally, we want to make sure we clean up when the element's removed using the onUnmounted
hook:
With this state now changing as the element enters/leaves the viewport, we can use this isInView
state to animate with CSS by swapping out classes:
Or to render different HTML entirely:
Scroll-triggered animations
We can also use inView
to trigger the animate
function itself. This can be useful if we want to trigger more complex animation sequences or animate transforms independently of each other.
Scroll-linked animations
The scroll
function can be used to link animations and functions to scroll progress by using Vue's template refs and lifecycle functions as before.
Next
With Motion set up in your Vue project, we recommend you follow the rest of the Quick Start guide to begin learning how to use Motion's animate
, scroll
and inView
functions.