el-table实现拖动排序--Sortable

471 阅读1分钟

el-table本身并不支持拖动排序,但是可以通过Sortable插件实现拖动。

  • 引入插件
    • npm install sortablejs --save
  • 页面中引用插件
    • import Sortable from 'sortablejs'
  • html页面
<el-table
    :data="retailBillingMethod"
    row-key="payType"
    class="my-table">
  <el-table-column
      label="姓名">
    <template slot-scope="scope">
      {{scope.row.payTypeName}}
    </template>
  </el-table-column>
  <el-table-column
      prop="description"
      label="学号">
  </el-table-column>
</el-table>
  • js页面
rowDrop() {
  const tbody = document.querySelector('.my-table .el-table__body-wrapper tbody');
  if (!tbody) {
    return
  }
  const that = this;
  Sortable.create(tbody, {
    animation: 180,
    delay: 0,
    onEnd({ newIndex, oldIndex }: any) {
      const currRow = that.retailBillingMethod.splice(oldIndex, 1)[0];
      that.retailBillingMethod.splice(newIndex, 0, currRow);
    },
  });
}
  • 遇到的问题
    • rowDrop()方法建议需要在mounted阶段调用,如果在created阶段调用,需要使用this.$nextTick包起来。
    • 如果出现,拖动之后,数据变了,但是视图没做同步更新,在el-table添加row-key="id",可以解决此问题。
  • 参考文献