useAniRef
A performant, event-driven Vue composable that binds animations directly to a template ref.
This composable applies animation styles directly to a DOM element, bypassing Vue's virtual DOM for high performance. It also includes a built-in event manager to simplify interactive animations.
Example
<script setup>
import { a } from "@freestylejs/ani-core";
import { useAniRef } from "@freestylejs/ani-vue";
// 1. Define the animation structure and timeline.
const myTimeline = a.dynamicTimeline(
a.sequence([
a.ani({ to: { x: 500, rotate: 360 }, duration: 1 }),
a.ani({ to: { x: 0, rotate: 0 }, duration: 1 }),
])
);
// 2. Use the composable to get the template ref and controller.
const [elementRef, controller] = useAniRef({
timeline: myTimeline,
initialValue: { x: 0, rotate: 0 },
// 3. Add event handlers for interactivity.
events: {
onMousedown: (ctx, event) => {
// The context `ctx` contains the current animation value and the controller.
ctx.play({ from: { x: ctx.x, rotate: ctx.rotate } });
},
onMouseup: (ctx) => {
ctx.pause();
},
},
});
</script>
<template>
<!-- 4. Bind the template ref to the element -->
<div
:ref="elementRef"
style="width: 100px; height: 100px; background: blue;"
@click="controller.play({ from: { x: 0, rotate: 0 } })"
/>
</template>Usage & Concepts
Overview
The useAniRef composable is designed for performance. It takes a configuration object (AniRefProps) and returns a template ref to be attached to a DOM element, along with the timeline controller. On each animation frame, it converts animation values to CSS styles and applies them directly to the element, avoiding Vue's VDOM overhead for the animated properties.
Event handlers passed to the events property receive a context object containing both the current animation value and the timeline controller, making it easy to build complex interactions.
When to Use
- Do use
useAniReffor high-performance animations of CSS properties liketransformandopacity. - Do use it for complex, interactive animations driven by user input at 60fps.
- Don't use
useAniRefwhen you need to read the animated values within your component's template or other computed properties. UseuseAnifor that.
Related Components
useAni- For reactive animations that integrate with Vue's Composition API.EventManager- The underlying utility used by theeventsproperty.