将图片通过拖拽添加到指定位置
<template>
<div class="draggle-box">
<img
class="draggle-source"
src="@/assets/bg/cat.jpg"
@dragstart="handleDragStart($event, '图片')"
/>
<div
class="draggle-target"
@dragover="handleDragOver"
@drop="handleDrop($event)"
></div>
</div>
</template>
<script setup>
import { ref, reactive } from "vue";
const handleDragStart = (event, props) => {
let draggleProps = {
src: event.target.getAttribute("src"),
type: props,
};
event.dataTransfer.setData("text/plain", JSON.stringify(draggleProps));
};
const handleDragOver = (event) => {
event.preventDefault();
};
const handleDrop = (event) => {
console.log(event);
event.preventDefault();
let draggleProps = JSON.parse(event.dataTransfer.getData("text/plain"));
let img = document.createElement("img");
img.src = draggleProps.src;
img.style.width = "100px";
img.style.height = "100px";
let text = document.createElement("text");
text.textContent = draggleProps.type;
event.target.appendChild(img);
event.target.appendChild(text);
};
</script>
<style scoped lang="less">
.draggle-box {
border: 1px solid black;
width: 600px;
height: 600px;
margin: 0 auto;
}
.draggle-target {
width: 200px;
height: 200px;
background-color: turquoise;
margin: 100px 0 100px 100px;
}
.draggle-source {
width: 100px;
height: 100px;
cursor: grab;
}
</style>
相关博文:看完就懂的前端拖拽那些事