<template>
<transition-group tag="div" name="drag" class="box">
<div
v-for="(item, index) in list"
:key="item"
class="item"
:draggable="true"
@dragstart="dragStart($event, index)"
@dragover="allowDrop"
@drop="drop($event, index, list)"
>
{{ item }}
</div>
</transition-group>
</template>
<script>
export default {
data() {
return {
list: [1, 2, 3, 4, 5, 6, 7, 8, 9]
};
},
methods: {
//取消默认行为
allowDrop(e) {
e.preventDefault();
},
//开始拖动
dragStart(e, index) {
e.dataTransfer.setData("index", index);
},
//放置
drop(e, index, data) {
this.allowDrop(e);
const dragIndex = e.dataTransfer.getData("index");
const temp = data.splice(dragIndex, 1);
data.splice(index, 0, temp[0]);
}
}
};
</script>
<style scoped>
.box {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
width: 330px;
margin: 0 auto;
}
.item {
width: 100px;
height: 100px;
border: 1px solid #ccc;
margin-bottom: 10px;
line-height: 100px;
text-align: center;
}
.drag-move {
transition: transform 1s;
}
</style>
网友评论