直接上代码吧,直接复制代码去调试
dragstart:当用户开始拖动一个元素或者一个选择文本的时候 dragstart 事件就会触发。
dragover:当元素或者选择的文本被拖拽到一个有效的放置目标上时,触发 dragover 事件。
dragend:拖放事件在拖放操作结束时触发。
<template>
<div>
<div v-if="imagesList && imagesList.length" class="image-list">
<div
v-for="(item,index) in imagesList"
:key="index"
class="drag-image-list"
draggable="true"
>
<el-image
:src="item"
alt=""
fit="cover"
@dragover="onDragOver" @dragend="onDragEnd(index)"
></el-image>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'draggable',
data() {
return {
imagesList: ["https://aimkang.oss-cn-shanghai.aliyuncs.com/202301/20230109014639250_9c2cd14e-b8db-439b-87b9-8e54bf0ac7ff.jpg",
"https://aimkang.oss-cn-shanghai.aliyuncs.com/202301/20230109014630841_9e3c7fe2-2b62-4d0e-964a-a7a4f3647c2b.png",
"https://aimkang.oss-cn-shanghai.aliyuncs.com/202301/20230109014632757_a1832b10-7b5c-4194-97e7-db9cc12a1170.png",
"https://aimkang.oss-cn-shanghai.aliyuncs.com/202301/20230109014634578_db794f5d-8d41-44eb-9c92-1ccb8a15c3f3.png",
"https://aimkang.oss-cn-shanghai.aliyuncs.com/202301/20230109014636894_979d34c5-2b88-4a6d-a122-ac398cc29c34.png"],
targetSrc: ''
}
},
methods: {
onDragOver(event) {
event.preventDefault()
const { src } = event.target
this.targetSrc = src
},
onDragEnd(index) {
const targetIdx = this.imagesList.indexOf(this.targetSrc);
[this.imagesList[index], this.imagesList[targetIdx]] = [this.imagesList[targetIdx], this.imagesList[index]]
this.imagesList = [...this.imagesList]
}
}
}
</script>
<style scoped lang="scss">
.image-list {
display: flex;
align-items: center;
justify-content: center;
.drag-image-list {
.el-image {
width: 148px;
height: 148px;
margin-right: 20px;
cursor: pointer;
}
}
}
</style>