vue sortablejs elementplus的虚拟表格进行列拖动问题

发布时间 2023-08-09 09:39:44作者: wwr01

遇到的问题是,在对列进行拖动之后,data数据交换成功,但是列名称没有交换;如果使用Table 表格就不会有这种问题;

初始页面如下:

 拖动列交换之后如下:

 数据列已经交换了,但是表头没有交换;

解决方法如下:

初始化代码如下:

 <template>
<
el-table-v2 :columns="columns" :data="dataList" expand-column-key="column-0" :width="700" :height="400" class="tableContent" row-key="groupCode" fixed />
</
template> //js代码中定义列的数组 const columns = ref([ { key: 'column-0', dataKey: 'column-0', title: 'Column 0', width: 150, fixed: 'left' }, { key: 'column-1', dataKey: 'column-1', title: 'Column 1', width: 150, fixed: 'left' }, { key: 'column-2', dataKey: 'column-2', title: 'Column 2', width: 150 }, { key: 'column-3', dataKey: 'column-3', title: 'Column 3', width: 150 }, { key: 'column-4', dataKey: 'column-4', title: 'Column 4', width: 150 }, { key: 'column-5', dataKey: 'column-5', title: 'Column 5', width: 150 }, { key: 'column-6', dataKey: 'column-6', title: 'Column 6', width: 150 }, { key: 'column-7', dataKey: 'column-7', title: 'Column 7', width: 150 }, { key: 'column-8', dataKey: 'column-8', title: 'Column 8', width: 150 }, { key: 'column-9', dataKey: 'column-9', title: 'Column 9', width: 150, fixed: 'right' }, ])

 

最初的代码如下:

const initSort = () => {
  const wrapperTr = document.querySelector('.tableContent .el-table-v2__header-row')
  Sortable.create(wrapperTr, {
    animation: 180,
    delay: 0,
    onEnd: (evt) => {
      const oldItem = columns.value[evt.oldIndex]
      columns.value.splice(evt.oldIndex, 1)
      columns.value.splice(evt.newIndex, 0, oldItem)
    },
  })

 解决问题的代码如下:

const initSort = () => {
  const wrapperTr = document.querySelector('.tableContent .el-table-v2__header-row')
  Sortable.create(wrapperTr, {
    animation: 180,
    delay: 0,
    // onEnd: (evt) => {
    //   const oldItem = columns.value[evt.oldIndex]
    //   columns.value.splice(evt.oldIndex, 1)
    //   columns.value.splice(evt.newIndex, 0, oldItem)
    // },
    onUpdate: function (event) {
      var newIndex = event.newIndex
      var oldIndex = event.oldIndex
      var div = wrapperTr.children[newIndex]
      var oldLi = wrapperTr.children[oldIndex]
      // 先删除移动的节点
      wrapperTr.removeChild(div)
      // 再插入移动的节点到原有节点,还原了移动的操作
      if (newIndex > oldIndex) {
        wrapperTr.insertBefore(div, oldLi)
      } else {
        wrapperTr.insertBefore(div, oldLi.nextSibling)
      }
      // 更新items数组
      const oldItem = columns.value[oldIndex]
      columns.value.splice(oldIndex, 1)
      columns.value.splice(newIndex, 0, oldItem)
    },
  })

  参考链接:Vue中使用Sortable - 简书 (jianshu.com)
其中说的第一种方法,是在columns中添加key,其实我已经加过了,但是没有效果;