vue实现拖拽交换位置

2022-07-15,,,

本文实例为大家分享了vue实现拖拽交换位置的具体代码,供大家参考,具体内容如下

<template>
  <div class="root">
    <transition-group tag="div" class="container">
      <div
        class="item"
        :class="'item' + i"
        v-for="(item, i) in items"
        :key="item.key"
        :style="{ 'background-color': item.color, border: '1px solid' }"
        draggable="true"
        @dragstart="handledragstart($event, item)"
        @dragover.prevent="handledragover($event, item)"
        @dragenter="handledragenter($event, item)"
        @dragend="handledragend($event, item)"
      >
        <div>{{ item }}</div>
      </div>
    </transition-group>
  </div>
</template>
 
<script>
export default {
  name: "toolbar",
  data() {
    return {
      items: [
        { key: 1, color: "#3883a0" },
        { key: 2, color: "#4883a0" },
        { key: 3, color: "#5883a0" },
        { key: 4, color: "#6883a0" },
        { key: 5, color: "#7883a0" },
        { key: 6, color: "#8883a0" },
        { key: 7, color: "#9883a0" },
      ],
      ending: null,
      dragging: null,
    };
  },
  methods: {
    handledragstart(e, item) {
      this.dragging = item;
    },
    handledragend(e, item) {
      if (this.ending.key === this.dragging.key) {
        return;
      }
      let newitems = [...this.items];
      const src = newitems.indexof(this.dragging);
      const dst = newitems.indexof(this.ending);
      newitems.splice(src, 1, ...newitems.splice(dst, 1, newitems[src]));
      console.log(newitems);
 
      this.items = newitems;
      this.$nexttick(() => {
        this.dragging = null;
        this.ending = null;
      });
    },
    handledragover(e) {
      // 首先把div变成可以放置的元素,即重写dragenter/dragover
      // 在dragenter中针对放置目标来设置
      e.datatransfer.dropeffect = "move";
    },
    handledragenter(e, item) {
      // 为需要移动的元素设置dragstart事件
      e.datatransfer.effectallowed = "move";
      this.ending = item;
    },
  },
};
</script>
 
<style lang="less" scoped>
.container {
  display: flex;
  flex-wrap: wrap;
}
.item {
  width: 200px;
  height: 200px;
  margin: 10px;
  color: #fff;
  transition: all linear 0.3s;
}
.item0 {
  width: 400px;
}
</style>

效果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《vue实现拖拽交换位置.doc》

下载本文的Word格式文档,以方便收藏与打印。