0
点赞
收藏
分享

微信扫一扫

vue3 中使用vue.draggable实现element-ui table 行、列拖拽

前言

最近在项目中碰到了element-ui 列表行、列拖拽的需求,就去找想找一个成熟的解决方法。但发现vue3的比较少,所以就把这个分享了出来,希望可以帮助到大家。

vue.draggable

vue.draggable是一款vue3的拖拽插件,是基于Sortable.js实现的,可以用它来拖拽列表、菜单、工作台、选项卡等常见的工作场景。

安装

    npm i -S vuedraggable@next

属性及方法

  • delay:number 定义鼠标选中列表单元可以开始拖动的延迟时间;
  • animation:number 单位:ms,定义排序动画的时间;
  • draggable:selector 格式为简单css选择器的字符串,定义哪些列表单元可以进行拖放;
  • onEnd:function 列表单元拖放结束后的回调函数;

image.png

示例代码

<template>
    <div class="draggable" style="padding: 20px">
        <el-table
                row-key="id"
                :data="state.tableData"
                style="width: 100%"
        >
            <el-table-column
                    v-for="(item,index) in state.oldList"
                    :key="`col_${index}`"
                    :prop="state.newList[index].prop"
                    :label="item.label"
                    align="center"
            >
            </el-table-column>
        </el-table>
    </div>
</template>
<script setup>
import Sortable from 'sortablejs';
import { reactive, onMounted} from 'vue';

const state = reactive({
    oldList: [],
    newList: [],
    tableData: [
        {
            id:1,
            name:'李四',
            gender:'男',
            age:20,
        },
        {
            id:2,
            name:'王五',
            gender:'未知',
            age:18,
        },
        {
            id:3,
            name:'张三',
            gender:'男',
            age:22,
        },
    ],
    tableConfig: {
        tableItems: [
            {
                label: '姓名',
                prop: 'name',
            },
            {
                label: '性别',
                prop: 'gender',
            },
            {
                label: '年龄',
                prop: 'age',
            },
        ]
    }
    
})
// 行拖拽
const rowDrop = function () {
    // 要拖拽元素的父容器
    const tbody = document.querySelector('.draggable .el-table__body-wrapper tbody');
    Sortable.create(tbody, {
        //  可被拖拽的子元素
        draggable: ".draggable .el-table__row",
        onEnd({newIndex, oldIndex}) {
            const currRow = state.tableData.splice(oldIndex, 1)[0];
            state.tableData.splice(newIndex, 0, currRow);
        }
    });
}
// 列拖拽
const columnDrop = function() {
    const wrapperTr = document.querySelector('.draggable .el-table__header-wrapper tr');
    Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: evt => {
            const oldItem = state.newList[evt.oldIndex];
            state.newList.splice(evt.oldIndex, 1);
            state.newList.splice(evt.newIndex, 0, oldItem);
        }
    });
}
onMounted(()=> {
    state.oldList = JSON.parse(JSON.stringify(state.tableConfig.tableItems))
    state.newList = JSON.parse(JSON.stringify(state.tableConfig.tableItems))
    columnDrop()
    rowDrop()
})
</script>

结语

本文到此结束

如果大家还有什么其他想法,欢迎在评论区交流!

举报

相关推荐

0 条评论