useSpring
useSpring is a simpler hook than useMotion and makes it possible to animate HTML or SVG Elements in your Vue components using spring animations.
Spring animations often feel more natural and fluid compared to linear animations, as they are based on the physics of a spring in the real world.
Springs maintain continuity for both static cases and cases with an initial velocity. This allows spring animations to adapt smoothly to user interactions like gestures.
useSpring can be bound to a HTML or SVG element, or to a simple object.
It skips the Variants system, allowing it to be as performant as using Popmotion natively, but with a nicer API to play with Vue refs.
Parameters
values
The values argument expects a motionProperties
object, which can be created using the useMotionProperties function.
spring
Spring animations can be configured in multiple ways, using spring options. The most intuitive way is using duration
and bounce
. Alternatively, you can use stiffness
, mass
, and damping
to configure a spring animation.
Under the hood, useSpring
uses Popmotion. See Spring options in Popmotion for a full list of spring options.
Passing a string
argument is optional. A default spring will be applied if you do not specify it.
Exposed
values
Values are an object representing the current state from your spring animations.
set
Set is function allowing you to mutate the values with the transition specified as spring parameter.
stop
Stop is a function allowing you to stop all the ongoing animations for the spring.
Example
In the example below, click the green box to animate it, or press the escape key to stop the animation.
<template>
<div class="container" tabindex="0" @keyup.esc="stop()">
<div ref="box" class="box" @click="animate">Click me</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
import { useSpring, useMotionProperties } from '@vueuse/motion'
const box = ref(null)
const { motionProperties } = useMotionProperties(box, {
x: 0,
y: 0,
})
const { set, stop } = useSpring(motionProperties, {
duration: 1000,
bounce: 0.0,
})
function animate() {
set({
x: Math.random() * 400,
y: Math.random() * 400,
})
}
</script>
<style scoped>
.container {
width: 500px;
height: 500px;
outline: 2px solid #41B883;
}
.box {
width: 100px;
height: 100px;
display: flex;
justify-content: center;
align-items: center;
background-color: #41B883;
color: white;
}
</style>