先看效果
多列布局拖拽
組件有替換和重排兩種方式税朴,默認(rèn)是重排方式受神,類似于手機(jī)九宮格的重排。
組件主要實(shí)現(xiàn)思路:計(jì)算出每個(gè)可拖拽組件的可移動(dòng)范圍,移動(dòng)之后計(jì)算出目標(biāo)位置的index帖蔓,如果方式為重排坊萝,重新排列數(shù)組順序宋下;如果為替換咙好,則直接替換數(shù)組中拖拽組件原始位置,以及最終位置的兩個(gè)數(shù)據(jù)
使用方式比較簡(jiǎn)單碱璃,給出展示數(shù)據(jù)以及列數(shù)即可弄痹,如下:
<template>
<uni-drag-group :column="3" :drag-data-list.sync="dragDataList" @drag-start="dragStart" @drag-end="dragEnd">
<template v-slot:default="dragData"><div class="drag-data-div" >這是{{ dragData.data }}數(shù)據(jù)</div></template>
</uni-drag-group>
</template>
<script>
export default {
data: function() {
return {
dragDataList: ['1', '2', '3', '4', '5', '6']
}
},
methods: {
dragStart: function(event) {
this.$message({
type: 'info',
message: `拖拽開始,通過console可以查看event參數(shù), ${JSON.stringify(event)}`
})
console.info('拖拽開始', event)
},
dragEnd: function(event, dragList) {
this.$message({
type: 'info',
message: `拖拽結(jié)束嵌器,通過console可以查看event參數(shù), ${JSON.stringify(event)}, ${dragList}`
})
console.info('拖拽結(jié)束', event, dragList)
}
}
}
</script>
<style scoped>
.drag-data-div {
background-color: green;
color: #FFFFFF;
width: 100px;
height: 100px;
line-height: 100px;
}
</style>
下面給出主要計(jì)算拖拽組件可移動(dòng)范圍的代碼:完整代碼請(qǐng)戳這里:傳送門
// 計(jì)算當(dāng)前元素可移動(dòng)的區(qū)域
getRangeOfEl: function(moveEl) {
const index = parseInt(moveEl.style.gridArea.split(' / ')[0].split('-')[1])
const res = {}
const currentColummn = index % this.column
res.minX = -((moveEl.offsetWidth + 5) * currentColummn)
res.maxX = (this.column - currentColummn - 1) * (moveEl.offsetWidth + 5)
const allRow = Math.ceil(this.dragList.length / this.column)
const currentRow = Math.floor(index / this.column)
res.minY = -((moveEl.offsetHeight + 5) * currentRow)
res.maxY = (allRow - currentRow - 1) * (moveEl.offsetHeight + 5)
return res
},
// 計(jì)算最終目標(biāo)位置的index值
getIndexOfMoveEL: function(moveEl) {
const x = parseInt(moveEl.style.left.split('px')[0])
const y = parseInt(moveEl.style.top.split('px')[0])
const index = parseInt(moveEl.style.gridArea.split(' / ')[0].split('-')[1])
let nowIndex = 0
if (x < 0) {
nowIndex = index - (Math.round(Math.abs(x) / moveEl.offsetWidth))
} else {
nowIndex = index + (Math.round(Math.abs(x) / moveEl.offsetWidth))
}
if (y < 0) {
nowIndex = nowIndex - (Math.round(Math.abs(y) / moveEl.offsetHeight)) * this.column
} else {
nowIndex = nowIndex + (Math.round(Math.abs(y) / moveEl.offsetHeight)) * this.column
}
return { nowIndex, index }
},