vue实现可拖拽列表

2023-12-15 01:21:34

直接上代码

<!-- vue实现可拖拽列表 -->
<template>
  <div>
    <button @click="logcolig">打印数据</button>
    <TransitionGroup name="list" tag="div" class="container">
      <div
        class="item"
        v-for="(item, i) in list"
        :key="item.id"
        :draggable="true"
        @dragstart="dragstart($event, i)"
        @dragenter="dragenter($event, i)"
        @dragend="dragend"
        @dragover="dragover"
      >
        {{ item.name }}
      </div>
    </TransitionGroup>
  </div>
</template>

<script>
let dragIndex = 0;

export default {
  created() {},
  mounted() {},
  beforeDestroy() {},
  props: {},
  data() {
    return {
      list: [
        { name: "a", id: 1 },
        { name: "b", id: 2 },
        { name: "c", id: 3 },
        { name: "d", id: 4 },
        { name: "e", id: 5 },
      ],
    };
  },
  //方法集合
  methods: {

    logcolig(){
      console.log(this.list);
    },
    dragstart(e, index) {
      e.stopPropagation();
      dragIndex = index;
      setTimeout(() => {
        e.target.classList.add("moveing");
      }, 0);
    },
    dragenter(e, index) {
      e.preventDefault();
      // 拖拽到原位置时不触发
      if (dragIndex !== index) {
        const source = this.list[dragIndex];
        this.list.splice(dragIndex, 1);
        this.list.splice(index, 0, source);

        // 更新节点位置
        dragIndex = index;
      }
    },
    dragover(e) {
      e.preventDefault();
      e.dataTransfer.dropEffect = "move";
    },
    dragend(e) {
      e.target.classList.remove("moveing");
    },
  },
};
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
.item {
  width: 200px;
  height: 40px;
  line-height: 40px;
  // background-color: #f5f6f8;
  background-color: skyblue;
  text-align: center;
  margin: 10px;
  color: #fff;
  font-size: 18px;
}

.container {
  position: relative;
  padding: 0;
}

.moveing {
  opacity: 0;
}

.list-move, .list-enter-active, .list-leave-active {
  transition: all 0.2s ease;
}
</style>

文章来源:https://blog.csdn.net/boundle_ss/article/details/134874732
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。