el-table implements list column dragging

1. First look at the needs:

        The original:

        

        want:

ps: The picture is not intuitive. The purpose is to allow columns to be dragged and displayed, so that certain columns can be displayed in the order you drag . The video cannot be uploaded, sorry!

1. First of all, the component library does not support column drag. OK, you can do it yourself and use other js libraries to implement it.

npm install sortablejs --save

If you are interested, you can check out the sortablejs official website.

2. Import the plug-in:

import Sortable from 'sortablejs'

3. Upload the code:

html: el-table component. I use encapsulation here. If there is no encapsulation, just use <el-table></el-table> directly.


      <!-- 表格数据,只展示和列拖拽相关的代码 -->
      <EleUITable
        :rowKey="columnDropId"
      >

js:

// 计算属性 给到上面的rowKey,且rowKwy必须绑定唯一值
 computed: {
    columnDropId() {
      this.customHeader.headData.forEach(e => {
        if (e.name) {
          return e.name
        } else {
          return e.type
        }
      })
    }
  },

// 生命周期
mounted(){
    this.dropCol = this.customHeader.headData
    this.getCustomHeader()
    this.columnDrop()
  },

// 方法
methods: {
    columnDrop() {
      const wrapperTr = document.querySelector('.el-table__header-wrapper tr')
      this.sortable = Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: evt => {
          const oldItem = this.dropCol[evt.oldIndex]
          this.dropCol.splice(evt.oldIndex, 1)
          this.dropCol.splice(evt.newIndex, 0, oldItem)
           // 下面是我自己的业务逻辑,同仁们可自行对自己的业务逻辑进行分析
          // this.customHeader.headData = this.dropCol
          // this.isColumnDrop = this.dropCol
        }
      })
    },

4. After copying the above code, have you encountered any bugs? I encountered a bug here. Bug: After dragging the column, the table header does not move, but the data moves, just like: the original table header is [1,2,3], swap the positions of table headers 1 and 2, But the header after dragging is still [1,2,3], but the data in headers 1 and 2 has changed. The reason is that v-for is used when encapsulating el-table, and the bound key value is not unique, which leads to this problem. Just make the key value unique.

Say one more thing:

        When using the el-table component before, one page used multiple el-tables, and the bound key values ​​were all i, which caused confusion in the table data. Therefore, it is best to ensure the uniqueness of this key value.

OK, if you have any questions, please ask them in time to avoid misleading others, thank you!

Guess you like

Origin blog.csdn.net/weixin_42234899/article/details/132664538