vue.js封装多列布局拖拽(grid布局)

2020-12-09  本文已影响0人  六时未至

先看效果

多列布局拖拽
组件有替换重排两种方式,默认是重排方式,类似于手机九宫格的重排。
组件主要实现思路:计算出每个可拖拽组件的可移动范围,移动之后计算出目标位置的index,如果方式为重排,重新排列数组顺序;如果为替换,则直接替换数组中拖拽组件原始位置,以及最终位置的两个数据
使用方式比较简单,给出展示数据以及列数即可,如下:
<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 }}数据</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参数, ${JSON.stringify(event)}`
      })
      console.info('拖拽开始', event)
    },
    dragEnd: function(event, dragList) {
      this.$message({
        type: 'info',
        message: `拖拽结束,通过console可以查看event参数, ${JSON.stringify(event)}, ${dragList}`
      })
      console.info('拖拽结束', event, dragList)
    }
  }
}
</script>
<style scoped>
.drag-data-div {
  background-color: green;
  color: #FFFFFF;
  width: 100px;
  height: 100px;
  line-height: 100px;
}
</style>

下面给出主要计算拖拽组件可移动范围的代码:完整代码请戳这里:传送门

// 计算当前元素可移动的区域
  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
  },
// 计算最终目标位置的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 }
  },
上一篇 下一篇

猜你喜欢

热点阅读