Skip to content

useDraggable

使元素可拖动。

¥Make elements draggable.

示例

Check the floating boxes

👋 Drag me!
I am at 48, 80
Renderless component
Position persisted in sessionStorage
51, 150
👋 Drag here!
Handle that triggers the drag event
I am at 56, 240
Not Use Captured Element
Dragging here will not work
61, 330

用法

¥Usage

vue
<script setup lang="ts">
import { 
useDraggable
} from '@vueuse/core'
import {
useTemplateRef
} from 'vue'
const
el
=
useTemplateRef
<HTMLElement>('el')
// `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>

设置 preventDefault: true 以覆盖浏览器中某些元素的默认拖放行为。

¥Set preventDefault: true to override the default drag-and-drop behavior of certain elements in the browser.

ts
const { 
x
,
y
,
style
} =
useDraggable
(el, {
preventDefault
: true,
// with `preventDefault: true` // you can disable the native behavior (e.g., for img) // and control the drag-and-drop, preventing the browser interference. })

组件用法

¥Component Usage

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

对于组件使用,可以将附加属性 storageKeystorageType 传递给组件并启用元素位置的持久性。

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

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