vue实现拖拽交换位置功能
vue实现拖拽交换位置功能
·
hmtl代码部分
<div
style="padding: 8px; cursor: pointer;"
:class="dataFieldIndex == i ? 'active' : ''"
v-for="(item, i) in assemblyData"
:key="i"
@mouseenter="dataFieldIndex = i"
@mouseleave="dataFieldIndex = -1"
draggable="true"
@dragstart="handleDragStart($event, item)"
@dragover.prevent="handleDragOver($event, item)"
@dragenter="handleDragEnter($event, item)"
@dragend="handleDragEnd($event, item)">
{{ item.label }}
</div>
然后在data内定义target=null和headstream=null
js代码部分
// 刚开始拖拽时触发
handleDragStart(e, item) {
this.headstream = item; //把刚开始拖拽的元素赋值给headstream
},
// 当拖拽元素在目标元素内时反复触发
handleDragOver(e) {
e.dataTransfer.dropEffect = "move";
},
// 当拖拽元素进入目标元素时触发
handleDragEnter(e, item) {
e.dataTransfer.effectAllowed = "move";// 为需要移动的元素设置dragstart事件
this.target = item; //把目标元素赋值给target
},
// 拖拽结束后触发
handleDragEnd(e, item) {
判断如果拖拽的元素等于目标元素就return
if (this.target.value === this.headstream.value) {
return;
}
let newItems = [...this.assemblyData];
const src = newItems.indexOf(this.headstream);
const dst = newItems.indexOf(this.target);
newItems.splice(src, 1, ...newItems.splice(dst, 1, newItems[src]));
this.assemblyData = newItems;
this.$nextTick(() => {
this.headstream = null;
this.target = null;
});
},
更多推荐
已为社区贡献1条内容
所有评论(0)