vue3+ts 原生 js drag drop 实现
<template>
<div>
<div
class="draggable"
draggable="true"
@dragstart="handleDragStart"
@dragend="handleDragEnd"
>
拖动我
</div>
<div
class="dropzone"
@dragover="handleDragOver"
@dragenter="handleDragEnter"
@dragleave="handleDragLeave"
@drop="handleDrop"
>
放置目标
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
setup() {
const handleDragStart = (event: DragEvent) => {
// 设置要传递的数据
event.dataTransfer?.setData('text', '拖动的数据');
};
const handleDragOver = (event: DragEvent) => {
// 阻止默认行为
event.preventDefault();
};
const handleDragEnter = (event: DragEvent) => {
// 添加视觉反馈
(event.target as HTMLElement).classList.add('hover');
};
const handleDragLeave = (event: DragEvent) => {
// 移除视觉反馈
(event.target as HTMLElement).classList.remove('hover');
};
const handleDrop = (event: DragEvent) => {
// 阻止默认行为
event.preventDefault();
// 添加数据
(event.target as HTMLElement).appendChild(document.getElementById('draggable') as HTMLElement);
};
return {
handleDragStart,
handleDragOver,
handleDragEnter,
handleDragLeave,
handleDrop,
};
},
});
</script>
<style>
.draggable {
width: 200px;
height: 50px;
cursor: move;
background-color: #222;
color: #fff;
text-align: center;
line-height: 50px;
border: 1px solid transparent;
}
.hover {
border-color: #000;
background-color: #ccc;
}
.dropzone {
width: 200px;
height: 50px;
background-color: #eee;
border: 1px dashed #ccc;
text-align: center;
line-height: 50px;
margin-top: 20px;
}
</style>
这段代码使用Vue 3和TypeScript实现了原生的拖拽(drag-and-drop)功能。它包括了拖拽的初始化、拖拽过程中的一些事件处理以及放置的逻辑。这个例子简单明了,并且注重于原生API的使用教学。
评论已关闭