hmtl代码部分

<div
    style="padding: 8px; cursor: pointer;"
    :class="dataFieldIndex == i ? 'active' : ''"
    v-for="(item, i) in assemblyData"
    :key="i"
    @mouseenter="dataFieldIndex = i"
    @mouseleave="dataFieldIndex = -1"
    draggable="true"
    @dragstart="handleDragStart($event, item)"
    @dragover.prevent="handleDragOver($event, item)"
    @dragenter="handleDragEnter($event, item)"
    @dragend="handleDragEnd($event, item)">
      {{ item.label }}
</div>

然后在data内定义target=null和headstream=null

js代码部分

// 刚开始拖拽时触发
    handleDragStart(e, item) {
      this.headstream = item; //把刚开始拖拽的元素赋值给headstream
    },
    // 当拖拽元素在目标元素内时反复触发
    handleDragOver(e) {
      e.dataTransfer.dropEffect = "move";
    },
    // 当拖拽元素进入目标元素时触发
    handleDragEnter(e, item) {
      e.dataTransfer.effectAllowed = "move";// 为需要移动的元素设置dragstart事件
      this.target = item; //把目标元素赋值给target
    },
    // 拖拽结束后触发
    handleDragEnd(e, item) {
      判断如果拖拽的元素等于目标元素就return
      if (this.target.value === this.headstream.value) {
        return;
      }
      let newItems = [...this.assemblyData];
      const src = newItems.indexOf(this.headstream);
      const dst = newItems.indexOf(this.target);
      newItems.splice(src, 1, ...newItems.splice(dst, 1, newItems[src]));
      this.assemblyData = newItems;
      this.$nextTick(() => {
        this.headstream = null;
        this.target = null;
      });
    },
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐