第一步: 第三方包下载
# 二选一
npm install vuedraggable
npm insall sortablejs

注意点:
vue中使用vuedraggable或者sortablejs实现,其实 vuedraggable依赖于 Sortable,当npm install vuedraggable时其实就有了 sortablejs
sortablejs相关配置,官方文档

第二步: 使用
// draggable 依赖于 Sortable,当npm install vuedraggable时其实就有了 sortablejs
import draggable from "vuedraggable";
import Sortable from "sortablejs";

全部代码

<template>
  <div class="home">
    <draggable element="ul" :list="tableData" @end="myend">
      <transition-group type="transition">
        <li v-for="(item, index) in tableData" :key="index">
          {{ item.name }}
        </li>
      </transition-group>
    </draggable>
    <hr />
    <!-- 一定要指定row-key 属性!,否则拖拽排序会出问题  -->
    <el-table :data="tableData" row-key="id">
      <el-table-column prop="id" label="ID"> </el-table-column>
      <el-table-column prop="name" label="姓名" width="180"> </el-table-column>
    </el-table>
  </div>
</template>

<script>
// draggable 依赖于 Sortable,当npm install vuedraggable时其实就有了 sortablejs
import draggable from "vuedraggable";
import Sortable from "sortablejs";

export default {
  name: "Home",
  data() {
    return {
      tableData: [
        {
          name: "这是line1",
          id: 1,
        },
        {
          name: "这是line2",
          id: 2,
        },
        {
          name: "这是line3",
          id: 3,
        },
        {
          name: "这是line4",
          id: 4,
        },
      ],
    };
  },
  created() {
    this.$nextTick(() => {
      this.drag();
    });
  },
  methods: {
    myend() {
      console.log(this.tableData);
    },
    drag() {
      const el = document.querySelectorAll(
        ".el-table__body-wrapper > table > tbody"
      )[0];
      Sortable.create(el, {
        disabled: false, // 拖拽不可用? false 启用
        ghostClass: 'sortable-ghost', //拖拽样式
        animation: 150, // 拖拽延时,效果更好看
        onEnd: (e) => { // 拖拽结束时的触发
            let arr = this.tableData; // 获取表数据
            arr.splice(e.newIndex, 0, arr.splice(e.oldIndex, 1)[0]); // 数据处理,获取最新的表格数据
            this.$nextTick(function () {
              this.tableData= arr;
              console.log(this.tableData)
            })
        },
      });
    },
  },
  components: {
    draggable,
  },
};
</script>
<style lang="less" type="text/less">
.sortable-ghost {
  opacity: 0.4;
  background-color: #f4e2c9;
}
</style>

Logo

前往低代码交流专区

更多推荐