Last active
October 31, 2022 17:44
-
-
Save blackmiaool/ccb74bc87eeeb71c864aeceaf197bdb4 to your computer and use it in GitHub Desktop.
sortable el-table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div ref="wrapper"> | |
<div :key="tableKey"> | |
<slot></slot> | |
</div> | |
</div> | |
</template> | |
<script> | |
/* | |
only for el-table | |
must be used as: | |
<SortableTable> | |
<el-table ...> | |
... | |
</el-table> | |
</SortableTable> | |
*/ | |
import sortable from "sortablejs"; | |
export default { | |
name: "SortableTable", | |
data() { | |
return { | |
tableKey: 0 | |
}; | |
}, | |
methods: { | |
makeTableSortAble() { | |
const table = this.$children[0].$el.querySelector( | |
".el-table__body-wrapper tbody" | |
); | |
sortable.create(table, { | |
handle: ".handle", | |
animation: 150, | |
onEnd: ({ newIndex, oldIndex }) => { | |
this.keepWrapperHeight(true); | |
this.tableKey = Math.random(); | |
const arr = this.$children[0].data; | |
const targetRow = arr.splice(oldIndex, 1)[0]; | |
arr.splice(newIndex, 0, targetRow); | |
} | |
}); | |
}, | |
keepWrapperHeight(keep) { | |
const wrapper = this.$refs.wrapper; | |
if (keep) { | |
wrapper.style.minHeight = `${wrapper.clientHeight}px`; | |
} else { | |
wrapper.style.minHeight = `auto`; | |
} | |
} | |
}, | |
mounted() { | |
this.makeTableSortAble(); | |
}, | |
watch: { | |
tableKey() { | |
this.$nextTick(() => { | |
this.makeTableSortAble(); | |
this.keepWrapperHeight(false); | |
}); | |
} | |
} | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment