<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>
从其他大佬那里抄来的,方便自己以后借鉴
标签:const,newList,element,state,splice,Sortable,拖拽 From: https://www.cnblogs.com/awench/p/17653779.html