前端Vue专辑

vue使用HTML 拖放 API(Drag and Drop)

2019-11-18  本文已影响0人  恍若如梦hzpeng

先看效果:


128f0fab-9995-47d1-9021-a5512b4a296a.gif

主要知识点还是HTML的API(Drag和Drop),详情看这里HTML 拖放 API - Web API 接口参考 | MDN

下面看代码:

<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>
data() {
  return {
    specificationList: ['大小', '颜色', '尺码', '重量', '尺寸'],
    dragIndex: '',  // 当前拖动元素的index
    enterIndex: ''  // 拖动进入该元素的index
  }
},

methods: {
  // 拖动事件
  handleDrag() {
    // console.log('drag')
  },

  handleDragover() {
    // 不能少并且要阻止默认行为,不然触发不了drop事件
  },

  // 拖动开始
    handleDragstart(index) {
    this.dragIndex = index;
  },

  // 拖动进入
  handleDragenter(index) {
    this.enterIndex = index;
  },

  // 拖动离开
  handleDragleave(){
    // this.enterIndex = '';
  },

  // 放开
  handleDrop() {
    const dropObj = this.specificationList[this.dragIndex];

    // 判断拖拽元素位置和目标位置的前后顺序
    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 = '';
    }
}
.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;
}
上一篇 下一篇

猜你喜欢

热点阅读