elementui+Sortablejs 实现 表格拖拽

1、安装依赖

npm install sortablejs --save

2、页面引入sortablejs依赖

import Sortable from 'sortablejs'

2、页面引入sortablejs依赖

<template>
  <div>
    <el-table :data="tableData" row-key="id">
        <el-table-column
            v-for="(item, index) in col"
            :key="`col_${index}`"
            :prop="col[index].prop"
            :label="item.label"
            align="center"
        ></el-table-column>
    </el-table>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
export default {
  data () {
    return {
      dateQuery: '',
      col: [
        { label: '日期', prop: 'date' },
        { label: '姓名', prop: 'name' },
        { label: '地址', prop: 'address' }
      ],
      dropCol: [
        { label: '日期', prop: 'date' },
        { label: '姓名', prop: 'name' },
        { label: '地址', prop: 'address' }
      ],
      tableData: [{
        date: '2016-05-02',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1518 弄'
      }, {
        date: '2016-05-04',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1517 弄'
      }, {
        date: '2016-05-01',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1519 弄'
      }, {
        date: '2016-05-03',
        name: '王小虎',
        address: '上海市普陀区金沙江路 1516 弄'
      }]
    }
  },
  mounted () {
    this.rowDrop()
    this.columnDrop()
  },
  created () {
  },
  methods: {
    // 行拖拽
    rowDrop () {
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      let data = []
      Sortable.create(tbody, {
        draggable: '.el-table__row',
        onEnd ({ newIndex, oldIndex }) {
          data = _this.tableData
        }
      })
      if (!data) {
        this.tableData = data
      }
    },
    // 列拖拽
    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)
        }
      })
    }
  }
}
</script>

<style>

</style>

  

 

posted @ 2022-08-22 18:31  玉文  阅读(14)  评论(0编辑  收藏  举报