el-table配合sortablejs实现拖拽 #146
Anuluca Date : 2023-05-29 Tags : 4
思路:
首先el-table上面row-class-name绑定要传的id,
然后将树形结构的数据转换成平铺的列表结构,
拖拽结束后的监听事件onEnd内可以获取到
通过拖拽可以获取到 旧数据 与 新数据对象以及拖拽后平铺的数据顺序,
这时可以通过拖拽后平铺的数据顺序配合parentId来知道当前层级的顺序和id
将这排好顺序的id数组传给后端,后端返回最新的数据
拖拽中事件监听onMove内可以阻止树形结构内的子集拖拽出去。
1.引入sortablejs
1
| npm install sortablejs --save
|
2.组件中使用
1
| import Sortable from 'sortablejs';
|
1
| <el-table :data="menuList" row-key="menuId" :row-class-name="tableClassNmae" :expand-row-keys="expandRowKeys" v-if="showFlag"></el-table>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| tableClassNmae(row){ return 'id=' + row.row.id + '' }
function treeToTile(treeData, childKey = 'children') { const arr = [] const expanded = data => { if (data && data.length > 0) { data.filter(d => d).forEach(e => { arr.push(e) expanded(e[childKey] || []) }) } } expanded(treeData) return arr }
let activeRows = reactive([]); let flag = true; let expandRowKeys=ref([]) let showFlag=ref([true]) let menuList=ref([]) onmounted(()=>{ const el = document.querySelector(".el-table__body-wrapper tbody"); const ops = { animation: 200, handle: ".el-table__row", ghostClass: "ghost", dataIdAttr: "class", onMove: ({ dragged, related }) => { activeRows = treeToTile(props.tdata) const oldRow = activeRows[dragged.rowIndex] const newRow = activeRows[related.rowIndex] if (oldRow.parentId !== newRow.parentId) { flag = false } else { flag = true }
return flag }, onEnd(evt) { activeRows = treeToTile(props.tdata) const oldRow = activeRows[evt.oldIndex] var arr = sortable2.toArray(); for (let index = 0; index < arr.length; index++) { arr[index] = arr[index].match(/(?<=\bid=)[\d]+/g)[0]; } let aa = activeRows.filter(d => d.parentId != oldRow.parentId).map(d => d.id); let bb = (arr.filter(d => aa.indexOf(d) == -1)) if (evt.oldIndex !== evt.newIndex) { if (flag) { showFlag.value=false; nextTick(()=>{ showFlag.value=true; menuList.value=res.data; expandRowKeys.value=[...e.parentId] }) expandRowKeys=[...oldRow.parentId] } } }, }; var sortable2 = Sortable.create(el, ops); })
|