👋 Drag me!
I am at 48, 80
ReferenceError: localStorage is not defined

useDraggable

Make elements draggable.

Usage

<script setup lang="ts">
import { ref } from 'vue'
import { useDraggable } from '.'

const el = ref<HTMLElement | null>(null)

// `style` will be a helper computed for `left: ?px; top: ?px;`
const { x, y, style } = useDraggable(el, {
  initialValue: { x: 40, y: 40 },
})
</script>

<template>
  <div ref="el" :style="style" style="position: fixed">
    Drag me! I am at {{x}}, {{y}}
  </div>
</template>

Component

<UseDraggable :initialValue="{ x: 10, y: 10 }" v-slot="{ x, y }">
  Drag me! I am at {{x}}, {{y}}
</UseDraggable>

For component usage, additional props storageKey and storageType can be passed to the component and enable the persistence of the element position.

<UseDraggable storage-key="vueuse-draggable" storage-type="session">
  Refresh the page and I am still in the same position!
</UseDraggable>

Type Declarations

export interface UseDraggableOptions {
  /**
   * Only start the dragging when click on the element directly
   *
   * @default false
   */
  exact?: MaybeRef<boolean>
  /**
   * Prevent events defaults
   *
   * @default false
   */
  preventDefault?: MaybeRef<boolean>
  /**
   * Element to attach `pointermove` and `pointerup` events to.
   *
   * @default window
   */
  draggingElement?: MaybeRef<
    HTMLElement | SVGElement | Window | Document | null
  >
  /**
   * Pointer types that listen to.
   *
   * @default ['mouse', 'touch', 'pen']
   */
  pointerTypes?: PointerType[]
  /**
   * Initial position of the element.
   *
   * @default { x: 0, y: 0}
   */
  initialValue?: MaybeRef<Position>
  /**
   * Callback when the dragging starts. Return `false` to prevent dragging.
   */
  onStart?: (position: Position, event: PointerEvent) => void | false
  /**
   * Callback during dragging.
   */
  onMove?: (position: Position, event: PointerEvent) => void
}
/**
 * Make elements draggable.
 *
 * @see https://vueuse.org/useDraggable
 * @param target
 * @param options
 */
export declare function useDraggable(
  target: MaybeRef<HTMLElement | SVGElement | null>,
  options?: UseDraggableOptions
): {
  position: Ref<Position>
  isDragging: ComputedRef<boolean>
  style: ComputedRef<string>
  x: Ref<number>
  y: Ref<number>
}

Source

SourceDemoDocs