useSpring
useSpring
是一个比 useMotion
更简单的 Hook,它可以使用弹簧动画在你的 Vue 组件中为 HTML 或 SVG 元素添加动画效果。
弹簧动画通常比线性动画感觉更自然和流畅,因为它们基于现实世界中弹簧的物理原理。
弹簧在静态情况和具有初始速度的情况下都保持连续性。这使得弹簧动画能够平滑地适应用户交互,如手势。
useSpring
可以绑定到 HTML 或 SVG 元素,或者绑定到一个简单的对象。
它跳过了 Variants 系统,使其性能与原生使用 Popmotion 一样出色,但提供了一个更友好的 API 来操作 Vue refs。
参数
values
values
参数需要一个 motionProperties
对象,可以使用 useMotionProperties
函数创建。
spring
弹簧动画可以通过多种方式配置,使用弹簧选项。最直观的方式是使用 duration
和 bounce
。或者,你可以使用 stiffness
、mass
和 damping
来配置弹簧动画。
在底层,useSpring
使用 Popmotion。有关弹簧选项的完整列表,请参阅Popmotion 中的弹簧选项。
传递 string
参数是可选的。如果你不指定,将应用默认弹簧。
公开
values
Values
是一个对象,表示弹簧动画的当前状态。
set
Set
是一个函数,允许你使用指定为 spring
参数的过渡来修改 values
。
stop
Stop
是一个函数,允许你停止弹簧的所有正在进行的动画。
示例
在下面的示例中,单击绿色框使其动画化,或按 Esc 键停止动画。
<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>