element table sortable.js(拖拽 行 列)

本文介绍了如何使用 Vue.js 和 Element UI 的 Table 组件结合 sortable.js 实现表格行和列的拖拽功能。通过设置 handle 类选择器实现拖拽操作,并强调了 row-key 的重要性,需确保其唯一以防止排序错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

js简单记录一下

先看效果图:

稍作修改:

项目需要点击按钮才能拖拽(handle: '.move', // handle's class )

二话不说直接上代码

<template>
<div>
    <el-table row-key="date" ref="table" border :data="tableData" style="width: 100%">
      <el-table-column prop="date" label="日期" width="180">
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="180">
      </el-table-column>
      <el-table-column prop="address" label="地址">
      </el-table-column>
       <el-table-column
      label="操作"
      width="100">
      <template slot-scope="scope">
        <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
        <el-button type="text" size="small">编辑</el-button>
        <div class="move">排序</div>
      </template>
    </el-table-column>
    </el-table>
    <pre>{{ tableData }}</pre>
</div>
</template>

js:注意:row-key必填且唯一(例如id),否则将排序出错

<script>
import Sortable from 'sortablejs';
export default {
  data() {
    return {
      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() {
    const table = document.querySelector('.el-table__body-wrapper tbody')
    const self = this
    Sortable.create(table, {
      handle:".move",
      onEnd({ newIndex, oldIndex }) {
        const targetRow = self.tableData.splice(oldIndex, 1)[0]
        self.tableData.splice(newIndex, 0, targetRow)
        console.log(self.tableData,'000')
      }
    })
  },
  methods:{
     handleClick(row) {
        console.log(row);
      }
  }
}
</script>

 列:

  //列拖拽
    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)
        }
      })
    }

列参考:element-UI ,Table组件实现拖拽效果 - 靳哲 - 博客园

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值