先看效果:
主要知識點(diǎn)還是HTML的API(Drag和Drop),詳情看這里HTML 拖放 API - Web API 接口參考 | MDN
下面看代碼:
- template
<Checkbox
class="hold"
draggable="true"
v-for="(item, index) in specificationList"
:key="index"
:class="{'hold-active': index === enterIndex, 'drag-active': index === dragIndex}"
@drag.native="handleDrag"
@dragover.native.prevent="handleDragover"
@dragstart.native="handleDragstart(index)"
@dragenter.native="handleDragenter(index)"
@dragleave.native="handleDragleave"
@drop.native.prevent="handleDrop"
>
{{ item }}
</Checkbox>
- script
data() {
return {
specificationList: ['大小', '顏色', '尺碼', '重量', '尺寸'],
dragIndex: '', // 當(dāng)前拖動元素的index
enterIndex: '' // 拖動進(jìn)入該元素的index
}
},
methods: {
// 拖動事件
handleDrag() {
// console.log('drag')
},
handleDragover() {
// 不能少并且要阻止默認(rèn)行為蒋荚,不然觸發(fā)不了drop事件
},
// 拖動開始
handleDragstart(index) {
this.dragIndex = index;
},
// 拖動進(jìn)入
handleDragenter(index) {
this.enterIndex = index;
},
// 拖動離開
handleDragleave(){
// this.enterIndex = '';
},
// 放開
handleDrop() {
const dropObj = this.specificationList[this.dragIndex];
// 判斷拖拽元素位置和目標(biāo)位置的前后順序
if (this.enterIndex >= this.dragIndex ) {
this.specificationList.splice(this.enterIndex + 1, 0, dropObj);
this.specificationList.splice(this.dragIndex, 1);
} else {
this.specificationList.splice(this.enterIndex, 0, dropObj);
this.specificationList.splice(this.dragIndex + 1, 1);
}
this.enterIndex = '';
this.dragIndex = '';
}
}
- style
.hold {
padding: 3px 5px;
border: 1px dashed transparent;
border-radius: 3px;
box-sizing: border-box;
}
.hold-active {
border: 1px dashed $baseColor;
}
.drag-active {
opacity: .5;
}