likes
comments
collection
share

vue2使用sortablejs实现el-table的行拖拽

作者站长头像
站长
· 阅读数 302
<!-- 全局组件 -->
<gl-dialog :title="dialogTitle" ref="dialog" top="2vh" :destroy-on-close="true" :visible.sync="visible" width="92%" @close="closeDialog">
      <!-- 全局组件-->
      <gl-table
        v-if="visible"
        height="750px"
        row-key="id"
        :ref="tableKey"
        :loading="loading"
        :column="filterColumns"
        :table-data="dataList"
        :total="dataCount"
        :show-total="false"
        :display-label="displayLabel"
        :sortChange="sortChange"
        :hidePagination="true"
        @pagination="handlePagination">
        <el-table-column label="操作" width="60" fixed="right" align="center" v-if="isEmptyData&&handleType==='edit'">
          <template slot-scope="{row}">
            <el-button size="mini" type="text" @click.stop="dialogHandle(row)">修改</el-button>
          </template>
        </el-table-column>
      </gl-table>

js部分

setSort() {
      const table = this.$refs[this.tableKey].$refs.multipleTable;
      // 获取el-table的tbody的dom节点
      const el = table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0];

      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
          const targetRow = this.dataList.splice(evt.oldIndex, 1)[0];
          // this.dataList是table的数据,通过splice进行替换,从而达到数据更新目的        
          this.dataList.splice(evt.newIndex, 0, targetRow);
          this.$nextTick(() => {
            table.doLayout();
          })
        }
      })
    },

css部分

.sortable-ghost { //setSort中绑定的class
  opacity: .8;
  color: #fff!important;
  background: #00BBB3!important;
  
}
::v-deep .editTable .el-table__body:hover {
  cursor: move;
}

注意事项:

  • 使用el-table进行行的拖拽的时候,一定需要使用属性row-key,这个需要进行diff;
  • 拖拽之后,表格如果有错位,可以调用el-table自带的方法 doLayout进行更新布局,这个最好是放在this.$nextTick()里面去执行;