Composables
useDraggable
Documentation for useDraggable composable.
The useDraggable composable wraps the createDraggable function from AnimeJS.
Type Definition
function useDraggable(
target: DraggableTypes["target"],
options?: DraggableOptions
): ProxyReturns<Draggable>
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.
Sample usage
const container = useTemplateRef('container')
const draggable = useTemplateRef('draggable')
useDraggable(draggable, {
container: container,
containerPadding: 4,
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 border border-primary/20 rounded-md border-dashed h-12"
>
<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!" />
</div>
</template>
@reference "~/assets/css/main.css";
.snap-positions {
@apply absolute inset-1 pointer-events-none;
}
.snap-positions div {
@apply absolute top-0 inset-y-0 left-(--snap-x);
}
0%
35%
75%
Return Value
Returns a ProxyReturns<Draggable> object. This is a reactive proxy that wraps the AnimeJS Draggable instance.
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!Example
const draggable = useDraggable('.square');
// Correct
const disable = () => draggable.disable?.();
// Wrong
const disable = () => draggable.disable();
API
Types
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;
export 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.