Vue3+element plus实现table拖拽排序(基于)

时间:2025-01-19 16:18:13
  • <script setup>
  • import Sortable from 'sortablejs';
  • const state = reactive({
  • UserAchieve: []
  • })
  • onMounted(() => {
  • nextTick(() => {
  • dragSort();
  • });
  • })
  • //行拖拽
  • const dragSort = () => {
  • let that = this;
  • // 首先获取需要拖拽的dom节点
  • const el1 = document.querySelectorAll('.el-table__body-wrapper')[0].querySelectorAll('table > tbody')[0];
  • Sortable.create(el1, {
  • disabled: false, // 是否开启拖拽
  • ghostClass: 'sortable-ghost', //拖拽样式
  • animation: 150, // 拖拽延时,效果更好看
  • group: { // 是否开启跨表拖拽
  • pull: false,
  • put: false
  • },
  • onEnd: (evt) => { //进行数据的处理,拖拽实际并不会改变绑定数据的顺序
  • const { newIndex, oldIndex } = evt
  • console.log(oldIndex,newIndex)
  • const currRow = state.UserAchieve?.splice(oldIndex, 1)[0]
  • state.UserAchieve?.splice(newIndex, 0, currRow)
  • sortIndex()
  • }
  • });
  • }
  • const sortIndex = () => {
  • const array = []
  • state.UserAchieve.forEach((e, i) => {
  • let obj = {
  • currency_id: e.currency_id,
  • index: i + 1
  • }
  • array.push(obj)
  • state.dictTableKey++;
  • })
  • }
  • watch(
  • () => state.dictTableKey,
  • () => {
  • nextTick(() => {
  • dragSort();
  • });
  • }
  • );
  • </script>