Composables
useDraggable
Documentation for useDraggable composable.
The useDraggable composable wraps the createDraggable function from AnimeJS.
Arguments
target
DraggableTypes['target'] required
The element(s) to make draggable. Supports CSS selectors, DOM elements, or template refs.
options
DraggableOptions
Configuration for dragging behavior. Highly reactive, supporting Vue refs and getters for most properties.
Example
0%
35%
75%
import { spring } from '#nanime/easings'
const container = useTemplateRef('container')
const draggable = useTemplateRef('draggable')
useDraggable(draggable, {
container: container,
releaseEase: spring({
bounce: 0.65,
duration: 400,
}),
x: {
snap: (draggable) => {
const hw = (draggable?.dragArea || [0, 0, 0, 0])[2]
const results = [0, hw * 0.35, hw * 0.75]
return results
},
},
})
<template>
<div ref="container" class="relative rounded-md border-dashed h-10">
<div class="snap-positions">
<div class="spot" style="--snap-x: 0%">0%</div>
<div class="spot" style="--snap-x: 35%">35%</div>
<div class="spot" style="--snap-x: 75%">75%</div>
</div>
<div ref="draggable" class="simple-box w-12 h-10! draggable" />
</div>
</template>
@reference "~/assets/css/main.css";
.snap-positions {
@apply absolute inset-0 pointer-events-none;
}
.snap-positions div {
@apply absolute top-0 inset-y-0 left-(--snap-x) w-12 h-10;
}
.draggable {
@apply z-10 text-black relative;
}
Return Value
Returns a ProxyReturns<Draggable> object. This is a reactive proxy that wraps the AnimeJS Draggable instance.
API
Types
function useDraggable(
target: DraggableTypes["target"],
options?: DraggableOptions
): ProxyReturns<Draggable>
type DraggableTargets = DOMTargetSelector | MaybeElementRef<HTMLElement | SVGElement | VueInstance | null> | null | undefined;
type DraggableTargetContainer = DraggableParams["container"] | MaybeElementRef<HTMLElement | VueInstance | null> | null | undefined;
type DraggableTargetTrigger = DraggableParams["trigger"] | DraggableTargets;
type DraggableTypes = {
target: DraggableTargets;
trigger: DraggableTargetTrigger;
container: DraggableTargetContainer;
}
type DraggableOptions = MakeRefable<Omit<DraggableParams, 'trigger' | 'container' | 'x' | 'y'> & {
trigger?: DraggableTypes["trigger"]
container?: DraggableTypes["container"]
x?: boolean | Prettify<MakeRefable<DraggableAxisParam, "snap", Draggable>>
y?: boolean | Prettify<MakeRefable<DraggableAxisParam, "snap", Draggable>>
}, RefableProps, Draggable>
See AnimeJS Draggable documentation for more details.
Notes
Because the draggable instance can be initialized after the component is mounted and only when the target is found,
properties and methods on the returned object may be
undefined until the initialization is complete.
Always use optional chaining or check for existence before calling methods!const draggable = useDraggable('.square');
// ✅ Correct
const disable = () => draggable.disable?.();
// ❌ Wrong
const disable = () => draggable.disable();