表格拖拽 拖拽排序 sortablejs插件

前言

我们开发后台的时候经常要做表格,有时候要对表格对一些其他的操作,今天我们是用sortablejs插件来实现我们的表格拖拽排序

1、首先要下载我们需要用到的插件
 npm install sortablejs
2、在使用的页面引入我们的插件
import Sortable from "sortablejs"; 
3、在表格上绑定ref
ref="singleTable"
4、定义我们的表格数组
data() {
    return {
        panList:[],
    };
  },
5、写操作逻辑
mounted() {
    this.dragSort();
  },
  methods: {
   sortableTable() {  
        const el = this.$refs.singleTable.$el.querySelectorAll(
        ".el-table__body-wrapper > table > tbody"
      )[0];
      Sortable.create(el, {  
        animation: 150,  
        onEnd: ({ newIndex, oldIndex }) => {  
          const movedItem = this.tableData.splice(oldIndex, 1)[0];  
          this.tableData.splice(newIndex, 0, movedItem);  
        },  
      });  
    },   
  },
6、这样就大功告成了
Vue 2中,要使用SortableJS插件表格内的数据项进行拖拽排序并添加点击事件,首先你需要安装SortableJS库以及Vue-Sortable-Table组件(如果你还没有安装的话)。你可以通过npm或yarn进行安装: ```bash npm install sortablejs @vue/sortable-table # 或者 yarn add sortablejs @vue/sortable-table ``` 接下来,创建一个SortableTable组件,并在其中绑定SortableJS实例。同时,设置`handleClick`函数监听点击事件: ```html <template> <div> <table :sortable="options" @click="handleClick"> <!-- 表格列和行 --> <tr v-for="(item, index) in items" :key="index"> <!-- 数据项和拖拽操作 --> <td contenteditable="true" :class="{ dragged: draggingItem === item }" @mousedown.prevent="startDrag(item)" @mouseup="endDrag(item)"> {{ item.value }} </td> <!-- 点击事件处理 --> <td @click="onRowClick(item)">点击</td> </tr> </table> </div> </template> <script> import Sortable from 'sortablejs'; export default { data() { return { items: [], // 初始化的数据数组 draggingItem: null, options: { group: '__items__', // 组名 animation: 150, // 动画效果时间 onSortEnd: (evt) => { this.updateOrder(evt.newIndex, evt.oldIndex); }, }, }; }, methods: { startDrag(item) { this.draggingItem = item; }, endDrag(item) { this.draggingItem = null; }, updateOrder(newIndex, oldIndex) { const newItems = [...this.items]; [newItems[newIndex], newItems[oldIndex]] = [newItems[oldIndex], newItems[newIndex]]; this.items = newItems; }, handleClick(item) { console.log('点击了第', item.index, '行'); // 这里可以根据需要处理点击事件 }, onRowClick(item) { this.handleClick(item); }, }, }; </script> ``` 在这个例子中,`handleClick`函数会在点击数据项时打印日志,你可以根据需求自定义这个功能。注意要在组件内部注册Sortable实例,并在`@click`事件上监听`onRowClick`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值