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>
相关推荐
拖孩1 分钟前
微信群太多,管理麻烦?那试试接入AI助手吧~
前端·后端·微信
快起来别睡了8 分钟前
看完你就知道JavaScript 中的对象创建与继承方式原来这么简单?!
javascript
乌兰麦朵18 分钟前
Vue吹的颅内高潮,全靠选择性失明和 .value 的PUA!
前端·vue.js
Goodbaibaibai18 分钟前
创建一个简洁的Vue3 + TypeScript + Vite + Pinia + Vue Router项目
javascript·vue.js·typescript
Code季风18 分钟前
Gin Web 层集成 Viper 配置文件和 Zap 日志文件指南(下)
前端·微服务·架构·go·gin
蓝倾18 分钟前
如何使用API接口实现淘宝商品上下架监控?
前端·后端·api
舂春儿20 分钟前
如何快速统计项目代码行数
前端·后端
毛茸茸20 分钟前
⚡ 从浏览器到编辑器只需1秒,这个React定位工具改变了我的开发方式
前端
Pedantic21 分钟前
我们什么时候应该使用协议继承?——Swift 协议继承的应用与思
前端·后端
Software攻城狮22 分钟前
vite打包的简单配置
前端