dragover
使用dragover实现的拖拽效果更加直观,拖拽过程就可以显示最终效果
<ul>
<li
class="add-item"
v-for="(item,index) in list"
:key="index"
draggable="true"
@dragstart="dragstart(item,index)"
@dragover="dragover(item,index)"
>
{{item.name}}
</li>
</ul>
data(){
return{
list:[
{
name:"123"
},{
name:"123"
},{
name:"123"
}
],
draggingItem: null,
lastItem: null,
}
}
//拖拽排序
dragstart(item, index) {
this.draggingItem = item;
},
dragover(item) {
let newList = [...this.clist];
if (item !== this.draggingItem && this.lastItem !== item) {
const fromIndex = newList.indexOf(this.draggingItem);
const toIndex = newList.indexOf(item);
const temp = newList[fromIndex];
newList[fromIndex] = newList[toIndex];
newList[toIndex] = temp;
this.list = [...newList]
}
this.lastItem = item;
},
dragenter
直到鼠标松开时才可以看到拖拽的最终效果
<ul>
<li
class="add-item"
v-for="(item,index) in list"
:key="index"
draggable="true"
@dragstart="dragstart(item,index)"
@dragenter="dragenter(index)"
@dragend="dragend()"
>
{{item.name}}
</li>
</ul>
data(){
return{
list:[
{
name:"123"
},{
name:"123"
},{
name:"123"
}
],
data:null,
startIndex:-1,
moveIndex:-1
}
}
dragstart(val, index) {
this.data = val;
this.startIndex = index;
},
dragend() {
if (this.startIndex != this.moveIndex) {
let newList = [...this.list];
// 删除老的节点
newList.splice(this.startIndex, 1);
// 增加新的节点(对数组第一个位置与最后位置做特殊处理,否则这两个位置有时会出错)
if (this.moveIndex == 0) {
newList.unshift(this.data);
} else if (this.moveIndex == this.list.length - 1) {
newList.push(this.data);
} else {
newList.splice(this.moveIndex, 0, this.data);
}
// list结构发生变化触发transition-group的动画
this.list = [...newList];
this.startIndex = -1;
}
},
// 记录移动过程中信息
dragenter(index) {
this.moveIndex = index;
},