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

1.安装   

 npm i -S vuedraggable@next

2.属性及一些方法

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

3.示例

<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>

GitHub 加速计划 / vu / Vue.Draggable
19.97 K
2.89 K
下载
SortableJS/Vue.Draggable: Vue.Draggable 是 Sortable.js 的 Vue.js 封装组件,提供了拖放排序功能,可以在 Vue 应用中轻松实现列表元素的可拖拽重排。
最近提交(Master分支:1 个月前 )
431db153 - 1 年前
017ab498 - 3 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐