Element-ui el-table 使用 SortableJS 实现表格拖拽

本文介绍了如何在Vue项目中使用SortableJS实现表格元素的拖拽排序,包括安装步骤、引入库、在模板中应用以及配置选项的详细说明。
摘要由CSDN通过智能技术生成

sortablejs文档

1、在项目目录下安装 sortablejs:

npm install sortablejs --save

2、在要实现表格拖拽的文件中引入 sortablejs:

import Sortable from 'sortablejs'

3、应用

<template>
    <el-table :data="tableData">
        <el-table-column label="用户Id" prop="id" align="center" />
        <el-table-column label="用户名" prop="username" align="center" />
    </el-table>
</template>

<script>
import Sortable from "sortablejs";

export default {
    data() {
        return {
            tableData: [{username:"a",id:1},{username:"b",id:2},{username:"c",id:3},{username:"d",id:4},],
        };
    },
    mounted() {
        this.initSort();
    },
    methods: {
		initSort() {
	      const el = document.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
	      // const sortable = new Sortable(el, options);
	      // 根据具体需求配置options配置项
	      const sortable = new Sortable(el, {
               // number 定义鼠标选中列表单元可以开始拖动的延迟时间;
             delay: 0,
	        onEnd: (evt) => { // 监听拖动结束事件
	          console.log(this) // this是当前vue上下文
	          console.log(evt.oldIndex) // 当前行的被拖拽前的顺序
	          console.log(evt.newIndex) // 当前行的被拖拽后的顺序
	          // 我们有了 evt.oldIndex 和 evt.newIndex 这两个参数做索引,我们可以根据绑定在表格上面的 data 这个 Array 找到两个相应的记录。就可以针对数据进行操作啦。
	          // 下面将拖拽后的顺序进行修改
	          const currRow = this.tableData.splice(evt.oldIndex, 1)[0]
	          this.tableData.splice(evt.newIndex, 0, currRow)
                console.log(this.datalist);
	        }
	      })
	    },
    },
};
</script>

相关配置

文档

(根据需求选择相应配置使用)

var sortable = new Sortable(el, {
        group: "name", // or { name: "...", pull: [true, false, 'clone', array], put: [true, false, array] }
        sort: true, // boolean 定义是否列表单元是否可以在列表容器内进行拖拽排序
        delay: 0, // number 定义鼠标选中列表单元可以开始拖动的延迟时间;
        touchStartThreshold: 0, // px, how many pixels the point should move before cancelling a delayed drag event
        disabled: false, // boolean 定义是否此sortable对象是否可用,为true时sortable对象不能拖放排序等功能,为false时为可以进行排序,相当于一个开关;
        store: null, // @see Store
        animation: 150, // ms, number 单位:ms,定义排序动画的时间
        easing: "cubic-bezier(1, 0, 0, 1)", // Easing for animation. Defaults to null. See https://easings.net/ for examples.
        handle: ".my-handle", // 格式为简单css选择器的字符串,使列表单元中符合选择器的元素成为拖动的手柄,只有按住拖动手柄才能使列表单元进行拖动
        filter: ".ignore-elements", // 过滤器,selector 格式为简单css选择器的字符串,定义哪些列表单元不能进行拖放,可设置为多个选择器,中间用“,”分隔;
        preventOnFilter: true, //  在触发过滤器`filter`的时候调用`event.preventDefault()`
        draggable: ".item", // 允许拖拽的项目类名
    	//ghostClass: drop placeholder的css类名  ,selector 格式为简单css选择器的字符串,当拖动列表单元时会生成一个副本作为影子单元来模拟被拖动单元排序的情况,此配置项就是来给这个影子单元添加一个class,我们可以通过这种方式来给影子元素进行编辑样式;
        ghostClass: "sortable-ghost", 
        chosenClass: "sortable-chosen", // 被选中项的css 类名,,当选中列表单元时会给该单元增加一个class;
        dragClass: "sortable-drag", // 正在被拖拽中的css类名
        dataIdAttr: "data-id",

        swapThreshold: 1, // Threshold of the swap zone
        invertSwap: false, // Will always use inverted swap zone if set to true
        invertedSwapThreshold: 1, // Threshold of the inverted swap zone (will be set to swapThreshold value by default)
        direction: "horizontal", // 拖拽方向 (默认情况下会自动判断方向)

        forceFallback: false, //boolean 如果设置为true时,将不使用原生的html5的拖放,可以修改一些拖放中元素的样式等;

        fallbackClass: "sortable-fallback", // string 当forceFallback设置为true时,拖放过程中鼠标附着单元的样式;
        fallbackOnBody: false, // 将cloned DOM 元素挂到body元素上。
        fallbackTolerance: 0, // Specify in pixels how far the mouse should move before it's considered as a drag.

        scroll: true, // boolean 默认为true,当排序的容器是个可滚动的区域,拖放可以引起区域滚动
        scrollFn: function (
          offsetX,
          offsetY,
          originalEvent,
          touchEvt,
          hoverTargetEl
        ) {}, // if you have custom scrollbar scrollFn may be used for autoscrolling
        scrollSensitivity: 30,
        // px, how near the mouse must be to an edge to start scrolling.
        scrollSpeed: 10, // px
        bubbleScroll: true, // apply autoscroll to all parent elements, allowing for easier movement

        dragoverBubble: false,
        removeCloneOnHide: true, // Remove the clone element when it is not showing, rather than just hiding it
        emptyInsertThreshold: 5, // px, distance mouse must be from empty sortable to insert drag element into it

        setData: function (
          /** DataTransfer */ dataTransfer,
          /** HTMLElement*/ dragEl
        ) {
          dataTransfer.setData("Text", dragEl.textContent); // `dataTransfer` object of HTML5 DragEvent
        },

        // 元素被选中
        onChoose: function (/**Event*/ evt) {
          evt.oldIndex; // element index within parent
        },

        // 元素未被选中的时候(从选中到未选中)
        onUnchoose: function (/**Event*/ evt) {
          // same properties as onEnd
        },

        // 开始拖拽的时候
        onStart: function (/**Event*/ evt) {
          evt.oldIndex; // element index within parent
        },

        // 结束拖拽
        onEnd: function (/**Event*/ evt) {
          var itemEl = evt.item; // dragged HTMLElement
          evt.to; // target list
          evt.from; // previous list
          evt.oldIndex; // element's old index within old parent
          evt.newIndex; // element's new index within new parent
          evt.clone; // the clone element
          evt.pullMode; // when item is in another sortable: `"clone"` if cloning, `true` if moving
        },

        // 元素从一个列表拖拽到另一个列表
        onAdd: function (/**Event*/ evt) {
          // same properties as onEnd
        },

        // 列表内元素顺序更新的时候触发
        onUpdate: function (/**Event*/ evt) {
          // same properties as onEnd
        },

        // 列表的任何更改都会触发
        onSort: function (/**Event*/ evt) {
          // same properties as onEnd
        },

        // 元素从列表中移除进入另一个列表
        onRemove: function (/**Event*/ evt) {
          // same properties as onEnd
        },

        // 试图拖拽一个filtered的元素
        onFilter: function (/**Event*/ evt) {
          var itemEl = evt.item; // HTMLElement receiving the `mousedown|tapstart` event.
        },

        // 拖拽移动的时候
        onMove: function (/**Event*/ evt, /**Event*/ originalEvent) {
          // Example: https://jsbin.com/nawahef/edit?js,output
          evt.dragged; // dragged HTMLElement
          evt.draggedRect; // DOMRect {left, top, right, bottom}
          evt.related; // HTMLElement on which have guided
          evt.relatedRect; // DOMRect
          evt.willInsertAfter; // Boolean that is true if Sortable will insert drag element after target by default
          originalEvent.clientY; // mouse position
          // return false; — for cancel
          // return -1; — insert before target
          // return 1; — insert after target
        },

        // clone一个元素的时候触发
        onClone: function (/**Event*/ evt) {
          var origEl = evt.item;
          var cloneEl = evt.clone;
        },

        // 拖拽元素改变位置的时候
        onChange: function (/**Event*/ evt) {
          evt.newIndex; // most likely why this event is used is to get the dragging element's current index
          // same properties as onEnd
        },
      });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值