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>
相关推荐
candyTong1 天前
一觉醒来,大模型就帮我排查完页面性能问题
前端·javascript·架构
魔术师Grace1 天前
我给 AI 做了场入职培训
前端·程序员
玩嵌入式的菜鸡1 天前
网页访问单片机设备---基于mqtt
前端·javascript·css
前端一小卒1 天前
我用 Claude Code 的 Superpowers 技能链写了个服务,部署前差点把服务器搞炸
前端·javascript·后端
滑雪的企鹅.1 天前
HTML头部元信息避坑指南大纲
前端·html
一拳不是超人1 天前
老婆天天吵吵要买塔罗牌,我直接用 AI 2 小时写了个在线塔罗牌
前端·ai编程
阿丰资源1 天前
SpringBoot+Vue实战:打造企业级在线文档管理系统
vue.js·spring boot·后端
excel1 天前
如何解决 Nuxt DevTools 中关于 unstorage 包的报错
前端
Rust研习社1 天前
使用 Axum 构建高性能异步 Web 服务
开发语言·前端·网络·后端·http·rust
C澒1 天前
AI 生码 - API2Code:接口智能匹配与 API 自动化生码全链路设计
前端·低代码·ai编程