elementUI+vue2+Sortable.js实现列拖拽(二级表头)
    		       		warning:
    		            这篇文章距离上次修改已过430天,其中的内容可能已经有所变动。
    		        
        		                
                要在Vue 2中使用Element UI和Sortable.js实现带有二级表头的列拖拽功能,你可以使用Sortable.js来实现列的拖拽,并且结合Element UI的表格组件来构建二级表头。以下是一个简化的例子:
- 安装Sortable.js:
npm install sortablejs --save- 在Vue组件中使用Sortable.js:
<template>
  <el-table
    :data="tableData"
    border
    style="width: 100%">
    <el-table-column
      v-for="item in draggableColumns"
      :key="item.prop"
      :prop="item.prop"
      :label="item.label">
      <el-table-column
        v-if="item.children"
        v-for="subItem in item.children"
        :key="subItem.prop"
        :prop="subItem.prop"
        :label="subItem.label">
      </el-table-column>
    </el-table-column>
  </el-table>
</template>
 
<script>
import Sortable from 'sortablejs';
 
export default {
  data() {
    return {
      tableData: [
        // ...数据
      ],
      draggableColumns: [
        {
          prop: 'date',
          label: 'Date',
          children: [
            { prop: 'date1', label: 'Date 1' },
            { prop: 'date2', label: 'Date 2' }
          ]
        },
        {
          prop: 'name',
          label: 'Name',
          children: [
            { prop: 'name1', label: 'Name 1' },
            { prop: 'name2', label: 'Name 2' }
          ]
        }
        // ...更多列
      ]
    };
  },
  mounted() {
    this.dragTable();
  },
  methods: {
    dragTable() {
      const dragTable = this.$el.querySelector('.el-table__header-wrapper tr');
      const dragCol = this.$el.querySelectorAll('.el-table__header-wrapper tr th');
      Sortable.create(dragTable, {
        animation: 180,
        delay: 0,
        onEnd: (evt) => {
          const oldItem = this.draggableColumns[evt.oldIndex];
          this.draggableColumns.splice(evt.oldIndex, 1);
          this.draggableColumns.splice(evt.newIndex, 0, oldItem);
        }
      });
      dragCol.forEach((col) => {
        col.addEventListener('click', () => {
          const table = this.$el.querySelector('.el-table');
          table.querySelectorAll('.el-table__body tr').forEach((row) => {
            const cells = row.querySelectorAll('td');
            const oldCell = col.cell;
            const newCell = cells[col.cellIndex];
            if (oldCell !== newCell) {
              col.cell.parentNode.replaceChild(newCell, col.cell);
              newCell.parentNode.replaceChild(oldCell, newCell);
              this.draggableColumns
评论已关闭