使用sortablejs实现ElementPlus el-table拖动每一行进行排序

  1. 安装sortable.js
npm install sortable.js

2.代码

<template>
    <div ref="tableRef">
        <el-table :data="dataList" :empty-text="'暂无数据'" stripe border>
            <el-table-column prop="level" label="排序" width="120">
                <template #default="{ row }">
                    <div class="flex items-center">
                        <span class="mr-sm">{{ row.level }}</span>
                        <el-icon class="drag-handle"><Sort /></el-icon>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="type" label="类型" min-width="120"> </el-table-column>
            <el-table-column prop="name" label="名称" min-width="120"> </el-table-column>
        </el-table>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue';
import Sortable from 'sortablejs';
import { Sort } from '@element-plus/icons-vue';

const dataList = ref<any[]>([
    {
        level: '1',
        type: '类型1',
        name: '名称1',
    },
    {
        level: '2',
        type: '类型2',
        name: '名称2',
    },
    {
        level: '3',
        type: '类型3',
        name: '名称3',
    },
    {
        level: '4',
        type: '类型4',
        name: '名称4',
    },
]);

/**
 * 是否可以拖拽
 */
function canDrag() {
    const can = dataList.value.every((item) => {
        return !item.isEdit;
    });
    return can;
}

function fastExtend(data: any) {
    return JSON.parse(JSON.stringify(data));
}

const tableRef = ref();
onMounted(() => {
    const tbody = tableRef.value.querySelector('.el-table__body-wrapper tbody');
    if (tbody) {
        Sortable.create(tbody, {
            animation: 150,
            handle: '.drag-handle',
            onMove: () => {
                console.log(canDrag());
                return canDrag();
            },
            onEnd: ({ oldIndex, newIndex }: any) => {
                if (!canDrag()) return;
                if (oldIndex === undefined || newIndex === undefined) return;
                const list = fastExtend(dataList.value);
                dataList.value = [];
                const currRow = list.splice(oldIndex, 1)[0];
                let newArr = [...list.slice(0, newIndex), currRow, ...list.slice(newIndex)];
                newArr.forEach((item, index) => {
                    item.level = index + 1 + '';
                });
                nextTick(() => {
                    dataList.value = newArr;
                });
            },
        });
    }
});
</script>
<style lang="scss" scoped>
.drag-handle {
    cursor: move;
    color: #666;
    font-size: 16px;
    &:hover {
        color: #409eff;
    }
}
</style>

3.效果图


69kcm-5xmh1.gif
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容