帮我用vue3和ts写一个拖拽指令
时间: 2023-07-01 16:16:40 浏览: 96
你好!下面是基于Vue3和TypeScript的简单拖拽指令:
```typescript
import { DirectiveBinding } from 'vue';
interface DragData {
el: HTMLElement;
startX: number;
startY: number;
deltaX: number;
deltaY: number;
}
export default {
mounted(el: HTMLElement, binding: DirectiveBinding) {
let dragData: DragData | null = null;
function handleMouseDown(event: MouseEvent) {
dragData = {
el,
startX: event.clientX,
startY: event.clientY,
deltaX: 0,
deltaY: 0,
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
}
function handleMouseMove(event: MouseEvent) {
if (dragData) {
dragData.deltaX = event.clientX - dragData.startX;
dragData.deltaY = event.clientY - dragData.startY;
el.style.transform = `translate(${dragData.deltaX}px, ${dragData.deltaY}px)`;
}
}
function handleMouseUp() {
if (dragData) {
dragData = null;
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
el.style.transform = '';
}
}
el.addEventListener('mousedown', handleMouseDown);
// 销毁时解绑事件
onUnmounted(() => {
el.removeEventListener('mousedown', handleMouseDown);
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
});
},
};
```
使用方式:在组件中使用 `v-drag` 指令即可,例如:
```vue
<template>
<div v-drag>拖拽我</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import drag from './drag';
export default defineComponent({
directives: {
drag,
},
});
</script>
```
这是一个最简单的拖拽指令,可以通过对 `handleMouseMove` 中的代码进行修改来实现更复杂的拖拽效果。
阅读全文