Sortable实现table拖拽功能

本文介绍如何使用 sortablejs 插件实现 Element UI 表格行的拖拽排序功能,通过 npm 安装并引入 sortablejs,在 Vue 项目中进行配置,使表格数据能够动态更新排序。

1.安装插件

npm install sortablejs --save

2.使用插件 

<template>
  <el-table :data="tableData" id="table" row-key="id" border style="width: 300px;">
      <el-table-column type="index" fixed width="50" label="序号"></el-table-column>
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column label="操作" width="70">
        <template slot-scope="scope">
          <i style="font-size: 24px; color: blue;" class="el-icon-menu"></i>
        </template>
      </el-table-column>
    </el-table>
</template>

<script>
import Sortable from 'sortablejs'
export default{
  name: 'tableEle',
  data () {
    return {
      tableData: [
        {
          name: '张三',
          id: 1
        },
        {
          name: '李四',
          id: 2
        },
        {
          name: '王五',
          id: 3
        },
        {
          name: '赵六',
          id: 4
        }
      ]
    }
  },
  created () {

  },
  mounted () {
    // 调用拖拽方法
    this.rowDrop()
  },
  methods: {
    // 行拖拽
    rowDrop () {
      const tbody = document.querySelector('#table tbody')
      const _this = this
      Sortable.create(tbody, {
        onEnd ({ newIndex, oldIndex }) {
          const currRow = _this.tableData.splice(oldIndex, 1)[0]
          _this.tableData.splice(newIndex, 0, currRow)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>

注意:1.一定要指定行的唯一标识 row-key="id"

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值