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>
相关推荐
老坛0014 分钟前
2025决策延迟的椭圆算子分析:锐减协同工具的谱间隙优化
前端
老坛0015 分钟前
从记录到预测:2025新一代预算工具如何通过AI实现前瞻性资金管理
前端
今禾8 分钟前
" 当Base64遇上Blob,图像转换不再神秘,让你的网页瞬间变身魔法画布! "
前端·数据可视化
华科云商xiao徐12 分钟前
高性能小型爬虫语言与代码示例
前端·爬虫
十盒半价13 分钟前
深入理解 React useEffect:从基础到实战的全攻略
前端·react.js·trae
攀登的牵牛花14 分钟前
Electron+Vue+Python全栈项目打包实战指南
前端·electron·全栈
iccb101314 分钟前
我是如何实现在线客服系统的极致稳定性与安全性的
前端·javascript·后端
一大树15 分钟前
Vue3祖孙组件通信方法总结
前端·vue.js
不要进入那温驯的良夜16 分钟前
跨平台UI自动化-Appium
前端
海底火旺17 分钟前
以一个简单的React应用理解数据绑定的重要性
前端·css·react.js