vue2实现元素拖拽

直接使用vue-draggable插件更好

以下是模仿代码

html 复制代码
<!--  -->
<template>
  <div>
    <button v-on:click="shuffle">Shuffle</button>
    <transition-group name="flip-list" tag="ul" class="box" ref="box">
      <li
        v-for="(item, index) in list"
        :key="item.text"
        class="list"
        :class="item.classList"
        draggable
        @dragstart="dragstart(item)"
        @dragenter="dragenter(item)"
        @dragend="dragend"
      >
        {{ item.text }}
      </li>
    </transition-group>
    <div>12312</div>
  </div>
</template>

<script>
// 记录被拖动的元素
let source;
export default {
  data() {
    return {
      list: [{ text: 1 }, { text: 2 }, { text: 3 }, { text: 4 }, { text: 5 }, { text: 6 }, { text: 7 }, { text: 8 }, { text: 9 }, { text: 10 }],
    };
  },
  created() {
    this.list = this.list.map((item) => {
      return {
        ...item,
        classList: [],
      };
    });
  },
  methods: {
    shuffle: function () {
      this.list.sort(() => Math.random() - 0.5);
    },
    dragstart(e) {
      source = e;
      setTimeout(() => {
        e.classList.push("moveing");
      }, 0);
    },
    dragenter(e) {
      if (e.text === source.text) return;
      this.changeSort(e);
    },
    dragend(e) {
      let _soucre = this.list.find((item) => item.text === source.text);
      let classIndex = _soucre.classList.findIndex((item) => item === "moveing");
      _soucre.classList.splice(classIndex, 1);
      source = null
    },
    // 与soucre元素交换位置
    changeSort(e) {
      const targetIndex = this.list.findIndex((item) => item.text === e.text);
      const sourceIndex = this.list.findIndex((item) => item.text === source.text);
      this.list.splice(targetIndex, 1, ...this.list.splice(sourceIndex, 1, this.list[targetIndex]));
    },
  },
};
</script>
<style lang="scss" scoped>
.box {
  display: flex;
  padding: 20px;
}
.list {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100px;
  height: 50px;
  margin-right: 10px;
  background-color: skyblue;
}

.moveing {
  background-color: gray;
}
.flip-list-move {
  transition: transform 0.5s;
}

.li {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100px;
  height: 50px;
  margin-bottom: 10px;
  background-color: skyblue;
}
</style>
相关推荐
东风西巷3 分钟前
Atlantis Word Processor:全方位的文字处理专家
前端·学习·word·软件需求
今天不要写bug15 分钟前
基于elementUI实现一个可编辑的表格(简洁版)
前端·javascript·elementui
上优17 分钟前
Vue3纯前端同源跨窗口通信移动AGV小车
前端·vue.js·状态模式
h_k1008618 分钟前
Chrome 插件开发入门技术文章大纲
前端·chrome
一只小阿乐18 分钟前
vue-router 的实现原理
前端·javascript·vue.js·路由·vue-router
小圣贤君18 分钟前
小说写作中的时间轴管理:基于 Vue 3 的事序图技术实现
vue.js·electron·写作·甘特图·时间轴·事序图
Zz_waiting.19 分钟前
案例开发 - 日程管理 - 第七期
开发语言·前端·javascript·vue.js·html·路由
writeone20 分钟前
9-10关于JS初学产生的问题
开发语言·javascript·ecmascript
一只小风华~23 分钟前
Vue:事件处理机制详解
前端·javascript·vue.js·typescript·前端框架
dy17174 小时前
element-plus表格默认展开有子的数据
前端·javascript·vue.js