一、实现效果

请添加图片描述

二、实现效果

实现原理: 主要依靠原生的 dragstartdragend 事件

当然:也可以基于插件 vue.draggable 实现

<!DOCTYPE html>
<html lang="en">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport"
    content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, width=device-width" />
  <title>test</title>
  <style type="text/css">
    .flip-list-move {
      transition: transform 0.3s ease-in;
    }

    .box {
      display: block;
      display: flex;
      width: 500px;
      flex-wrap: wrap;
    }

    .items {
      width: 100px;
      height: 50px;
      margin: 10px;
      line-height: 50px;
      text-align: center;
      border: 2px solid red;
      border-radius: 4px;
      cursor: move;
      background: #eee;
    }

    .items.active {
      background: rgba(0, 0, 0, 0.4);
    }
  </style>
</head>

<body>
  <div id="content">
    <transition-group name="flip-list" class="box">
      <div v-for="item in items" :key="item" draggable="true" class="items"
        :class="{active: oldVal == item && isActive==item}" @dragstart="dragstart(item)" @dragenter="dragenter(item)"
        @dragend="dragend(item)">
        {{item}}
      </div>
    </transition-group>
  </div>
  <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
  <script>
    var vue = new Vue({
      el: '#content',
      data: {
        items: [1, 2, 3, 4, 5, 6, 7, 8, 9],
        isActive: 0,
        oldVal: 0,
        newOld: 0,
      },
      methods: {
        dragstart(val) {
          // 保存旧的节点和当前正在操作的节点
          this.oldVal = val;
          this.isActive = val;
          console.log('-------dragstart val', val);
          console.log('-------dragstart this.oldVal', this.oldVal);
          console.log('-------dragstart this.isActive', this.isActive);
        },
        dragend(val) {
          if (this.oldVal != this.newOld) {
            let oldIndex = this.items.indexOf(this.oldVal);
            let newIndex = this.items.indexOf(this.newOld);
            let newItems = [...this.items];
            // 删除老的节点
            newItems.splice(oldIndex, 1);
            // 增加新的节点
            newItems.splice(newIndex, 0, this.oldVal);
            // items结构发生变化触发transition-group的动画
            this.items = [...newItems];
            // 重置正在操作的节点
            this.isActive = -1;
          }
        },
        // 记录移动过程中信息
        dragenter(val) {
          // 即保存要将当前移动的节点放到那个位置
          this.newOld = val;
          console.log('-----------dragenter val', val);
          console.log('-----------dragenter this.newOld', this.newOld);
        },
      },
    });
  </script>
</body>

</html>

文章仅为本人学习过程的一个记录,仅供参考,如有问题,欢迎指出!

Logo

前往低代码交流专区

更多推荐