效果如图所示
<template>
<div class="wrap">
<transition-group tag="div" class="container">
<div class="card" v-for="(item,index) in items" :key="item.key"
draggable="true"
@dragstart="handleDragStart($event, item)"
@dragover.prevent="handleDragOver($event, item)"
@dragenter="handleDragEnter($event, item)"
@dragend="handleDragEnd($event, item)"
@click="handleChange($event, item)"
>
<div v-if="item.key==1" class="front">
第一层内容
</div>
<div v-else class="back">
第二层内容
</div>
</div>
</transition-group>
</div>
</template>
data() {
return {
items: [
{ key: 1,},
{ key: 2,}
],
dragging: null
};
},
methods: {
changeIndex(index){
this.currentIndex = !this.currentIndex;
console.log(index)
},
handleDragStart(e,item){
console.log(1111)
this.dragging = item;
},
handleDragEnd(e,item){
this.dragging = null
console.log(2222)
},
handleChange(e,item){
// e.dataTransfer.dropEffect = 'move'
// e.dataTransfer.effectAllowed = "move"
const newItems = [...this.items]
console.log(newItems)
const src = newItems.indexOf(this.dragging)
const dst = newItems.indexOf(item)
newItems.splice(dst, 0, ...newItems.splice(src, 1))
this.items = newItems
},
//首先把div变成可以放置的元素,即重写dragenter/dragover
handleDragOver(e) {
e.dataTransfer.dropEffect = 'move'// e.dataTransfer.dropEffect="move";//在dragenter中针对放置目标来设置!
},
handleDragEnter(e,item){
e.dataTransfer.effectAllowed = "move"//为需要移动的元素设置dragstart事件
if(item === this.dragging){
return
}
const newItems = [...this.items]
console.log(newItems)
const src = newItems.indexOf(this.dragging)
const dst = newItems.indexOf(item)
newItems.splice(dst, 0, ...newItems.splice(src, 1))
this.items = newItems
}
},
.wrap {
display: flex;
justify-content: center;
.container{
left: 0;
display:flex;
flex-direction: column;
padding: 0;
}
.card {
width: 195px;
height: 295px;
margin-top: 100px;
//transition: all linear .3s
transition: 0.5s linear transform;
border-radius: 10px;
box-shadow:1px 1px 8px 1px #6eaeae;
cursor:pointer;
}
.card:first-child{
position: absolute;
float: left;
transform: scale(0.9);
background: greenyellow;
}
.card:last-child{
position: absolute;
float: left;
margin-left: -100px;
transform: scale(1);
background: deepskyblue;
}
.front {
border-radius: 10px;
padding: 10px;
}
.back {
border-radius: 10px;
padding: 10px;
}
}