VueUse useDraggable 拖动元素

VueUse useDraggable 可以拖动元素到任何位置,并返回对应的坐标。

vue.draggable

useDraggable功能比较有限,建议使用vue.draggable这种专业的拖拽组件支持Vue,该网站包含了vue3、vue2和纯js版本,中文文档网址:https://www.itxst.com/vue-draggable/tutorial.html 。

代码示例

<script setup lang="ts">
import { ref } from 'vue'
import { useDraggable } from '@vueuse/core'

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

// 初始化,包括起始位置
const { x, y, style } = useDraggable(el, {
  initialValue: { x: 60, y: 60 },
})
</script>
<template>
  <div ref="el" :style="style" style="position: fixed">
    Drag me! I am at {{x}}, {{y}}
  </div>
</template>

组件示例

需要安装@vueuse/components库,如果没安装请先安装。

npm i @vueuse/core @vueuse/components
<UseDraggable :initialValue="{ x: 10, y: 10 }" v-slot="{ x, y }">
  Drag me! I am at {{x}}, {{y}}
</UseDraggable>

例子