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

先看效果:


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

主要知識點(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)前拖動(dòng)元素的index
    enterIndex: ''  // 拖動(dòng)進(jìn)入該元素的index
  }
},

methods: {
  // 拖動(dòng)事件
  handleDrag() {
    // console.log('drag')
  },

  handleDragover() {
    // 不能少并且要阻止默認(rèn)行為,不然觸發(fā)不了drop事件
  },

  // 拖動(dòng)開始
    handleDragstart(index) {
    this.dragIndex = index;
  },

  // 拖動(dòng)進(jìn)入
  handleDragenter(index) {
    this.enterIndex = index;
  },

  // 拖動(dòng)離開
  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;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • WWDC 2017 剛結(jié)束,雖然如預(yù)期的一樣,缺少意料之外的驚喜,但依舊有不少新的特性和 API 值得圈點(diǎn)。拋開 ...
    MrPeak閱讀 5,281評論 2 36
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom閱讀 3,135評論 0 3
  • Awesome Ruby Toolbox Awesome A collection of awesome Ruby...
    debbbbie閱讀 3,071評論 0 3
  • # Awesome Python [![Awesome](https://cdn.rawgit.com/sindr...
    emily_007閱讀 2,323評論 0 3
  • 今天是祖國成立70周年華誕。全國各族人民舉行各種各樣的慶?;顒?dòng),以不同的方式給偉大的祖國送上最美好的祝福...
    梁鴻昌524閱讀 104評論 0 2

友情鏈接更多精彩內(nèi)容