实现两个盒子内元素位置任意互换,主要原理是在标签上加入draggable可移动属性,dragstart拖拽开始,记录下拖拽的索引和所在的盒子,方便后边操作数组,dragenter拖拽移入元素时触发,通过移入的元素,判断索引和所在的盒子,进行位置互换,dragover拖拽移除元素执行,由于咱们这个是dragenter进行互换的,所以没有用到
css部分
.list {
list-style: none;
display: flex;
height: 200px;
background-color: #CCC;
margin-bottom: 100px;
padding-top: 50px;
.drag-move {
transition: transform 0.3s;
}
.list-item {
cursor: move;
width: 240px;
background: #EA6E59;
border-radius: 4px;
color: #FFF;
margin-bottom: 6px;
margin-right: 50px;
height: 50px;
line-height: 50px;
text-align: center;
}
.bottom-item{
background: #6595ee;
}
.default-item{
cursor: move;
width: 240px;
border: 1px dashed #666;
border-radius: 4px;
color: #666;
margin-bottom: 6px;
margin-right: 50px;
height: 50px;
line-height: 50px;
text-align: center;
}
}
body部分
<div id="app">
<transition-group name="drag" class="list" tag="ul">
<li
@dragstart="dragstart(index,'top')"
@dragenter="dragenter($event, index,'top')"
@dragover.prevent
@drop="dragdrop($event, index)"
draggable
v-for="(item, index) in list1"
:key="item.label"
class="list-item"
>
{{ item.label }}
</li>
<li v-if="list1.length == 0"
@dragstart="dragstart(0,'top')"
@dragenter="dragenter($event, 0,'top')"
@dragover.prevent
@ondrop="dragdrop($event, 0)"
key="移动添加"
class="default-item"
>
移动添加
</li>
</transition-group>
<transition-group name="drag" class="list" tag="ul">
<li
@dragstart="dragstart(index,'bot')"
@dragenter="dragenter($event, index,'bot')"
@dragover.prevent
@ondrop="dragdrop($event, index)"
draggable
v-for="(item, index) in list2"
:key="item.label"
class="list-item bottom-item"
>
{{ item.label }}
</li>
<li v-if="list2.length == 0"
@dragstart="dragstart(0,'bot')"
@dragenter="dragenter($event, 0,'bot')"
@dragover.prevent
@ondrop="dragdrop($event, 0)"
key="移动添加"
class="default-item"
>
移动添加
</li>
</transition-group>
</div>
js部分
data(){
return{
list1: [
{ label: "元素1" },
{ label: "元素2" },
{ label: "元素3" },
{ label: "元素4" },
{ label: "元素5" },
{ label: "元素6" },
],
list2: [],
dragIndex: "",
startIndex: "",
startName: "",
}
},
methods: {
dragstart(index, name) {
this.startName = name
this.startIndex = index
this.dragIndex = index;
console.log(index,'开始')
},
dragdrop(e, index){
console.log(index, '结束')
},
dragenter(e, index, name) {
console.log(this.dragIndex,index, '移动')
if(this.startName == 'top' && name == 'top'){
const moving = this.list1[this.dragIndex];
this.list1.splice(this.dragIndex, 1);
this.list1.splice(index, 0, moving);
}
if(this.startName == 'top' && name == 'bot'){
const moving = this.list1[this.dragIndex];
this.list1.splice(this.dragIndex, 1);
this.list2.splice(index, 0, moving);
}
if(this.startName == 'bot' && name == 'bot'){
const moving = this.list2[this.dragIndex];
this.list2.splice(this.dragIndex, 1);
this.list2.splice(index, 0, moving);
}
if(this.startName == 'bot' && name == 'top'){
const moving = this.list2[this.dragIndex];
this.list2.splice(this.dragIndex, 1);
this.list1.splice(index, 0, moving);
}
this.startName = name
this.dragIndex = index
},
}