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>
相关推荐
JayceM1 小时前
Vue中v-show与v-if的区别
前端·javascript·vue.js
HWL56791 小时前
“preinstall“: “npx only-allow pnpm“
运维·服务器·前端·javascript·vue.js
咪咪渝粮1 小时前
JavaScript 中constructor 属性的指向异常问题
开发语言·javascript
德育处主任1 小时前
p5.js 掌握圆锥体 cone
前端·数据可视化·canvas
mazhenxiao2 小时前
qiankunjs 微前端框架笔记
前端
无羡仙2 小时前
事件流与事件委托:用冒泡机制优化前端性能
前端·javascript
秃头小傻蛋2 小时前
Vue 项目中条件加载组件导致 CSS 样式丢失问题解决方案
前端·vue.js
CodeTransfer2 小时前
今天给大家搬运的是利用发布-订阅模式对代码进行解耦
前端·javascript
睡不着先生2 小时前
`text-wrap: balance` 实战指南:让多行标题自动排版更优美
css
阿邱吖2 小时前
form.item接管受控组件
前端