Vue.js学习笔记(七)使用sortablejs或el-table-draggable拖拽ElementUI的el-table表格组件


前言

记录 el-table-draggable 插件使用方法。


一、el-table-draggable是什么?

el-table-draggable的存在就是为了让vue-draggable支持element-ui中的el-table组件,让表格可以进行行列拖动等功能。

项目地址:https://gitcode.com/gh_mirrors/el/el-table-draggable

二、使用步骤

1.安装使用

npm i -S el-table-draggable

(示例):拖动修改数据排序,输入修改逻辑为,【1,2,3,4】,修改2为3,则3-1。

<template>
	<el-table-draggable @input="dragInputHandler">
		<el-table :data="tableData" row-key="id" v-loading="loading" size="mini" 
		max-height="500px">
			<el-table-column label="展示排序" width="160" prop="sort" align="center" sortable>
              <template slot-scope="{row}">
                <el-input-number v-model="row.newSort" controls-position="right" :min="1"
                  @change="(newSort) => { editSort(row, newSort) }" @blur="() => {
                if (!row.newSort) { $message.warning('序号不能为空'); row.newSort = row.sort;};
                if (Number(row.newSort) <= 0) { $message.warning('序号不能小于1'); row.newSort= row.sort; };
                  }"></el-input-number>
              </template>
            </el-table-column>
          </el-table>
        </el-table-draggable>
</template>


import ElTableDraggable from "el-table-draggable";
export default {
 components: {
    ElTableDraggable,
  },
 methods:{
    /** 输入修改排序 */
    editSort(row, rowSort) {
      if (!rowSort) return;
      const oldSort = Number(row.sort);
      const newSort = Math.min(Number(rowSort), this.tableData.length);
      this.$nextTick(() => {
        this.tableData = this.tableData.map((item) => {
          const itemData = { ...item };
          if (itemData.id === row.id) {
            itemData.sort = newSort;
            itemData.newSort = newSort;
          } else if (oldSort < newSort) {
            if (itemData.sort > oldSort && itemData.sort <= newSort) {
              itemData.sort -= 1;
              itemData.newSort -= 1;
            }
          } else if (oldSort > newSort) {
            if (itemData.sort >= newSort && itemData.sort < oldSort) {
              itemData.sort += 1;
              itemData.newSort += 1;
            }
          }
          return itemData;
        });
      })
    },
     /** 拖拽排序 */
    dragInputHandler(data) {
      this.$nextTick(() => {
        this.tableData = data.map((item, index) => { return { ...item, sort: index + 1,newSort: index + 1 } });
      });
    },
  },
}

2.sortablejs

el-table-draggable插件是基于sortablejs进行封装的,如果已经安装了sortablejs,想实现element的el-table拖拽,则可以进行以下操作。

<template>
    <el-table ref="tableList" :data="tableList" row-key="id" tooltip-effect="dark" 
    max-height="500"  border v-loading="loading" class="draggable">
      <el-table-column label="拖拽排序" width="80" align="center">
        <template slot-scope="{ row }">
          <i class="el-icon-rank allowDrag" style="cursor:pointer"></i>
        </template>
      </el-table-column>
     </el-table>
</template>


import Sortable from "sortablejs";
export default {
 mounted() {
	this.$nextTick(() => {
        this.lineDrop();
	});
 },
 methods:{
     /** 拖拽 */
    lineDrop() {
      const tbody = document.querySelector(".draggable .el-table__body-wrapper tbody");
      const _this = this;
      new Sortable(tbody, {
        animation: 150,
        ghostClass: "ghostClass",
        handle: ".allowDrag",//设置操作区域
        onEnd(evt) {
          const newIndex = evt.newIndex;
          const row = _this.tableList[newIndex];
          const oneRow = _this.tableList[newIndex - 1];
          hotLangSort({
            id: oneRow.id,
            langId: _this.searchParams.langId,
            sort: row.sort,
            type: _this.activeTab === 'series' ? 0 : 1
          }).then(res => {
            _this.$message.success('操作成功')
            _this.$parent.getInfo();
            _this.getInfo()
          }).catch(err => { _this.$message.error('操作失败') }).finally(() => { })
        }
      })
    },
 }
}

在这里插入图片描述


总结

以上为拖拽插件学习记录。

SortableJS是一个强大的JavaScript库,用于创建拖放排序功能。在Vue3中使用SortableJS,首先你需要安装它。你可以通过npm或yarn命令行工具添加依赖: ```bash # npm npm install sortablejs @vueuse/core # yarn yarn add sortablejs @vueuse/core ``` 然后,在Vue组件中引入并使用SortableJS,可以借助`@vueuse/core`库提供的插件式API。这里是一个简单的例子: ```html <template> <div id="draggableItems"> <div v-for="(item, index) in items" :key="index" class="ui-element"> {{ item.name }} <button @click="swap(index, index + 1)">Swap</button> </div> </div> </template> <script setup> import { ref } from 'vue' import Sortable from '@sortablejs/react' const items = ref([{ name: 'Item 1' }, { name: 'Item 2' }, { name: 'Item 3' }]) let activeSortable = null function swap(indexA, indexB) { const [temp] = items.value.splice(indexA, 1) items.value.splice(indexB, 0, temp) } function initSortable() { if (!activeSortable) { activeSortable = new Sortable('#draggableItems', { group: '__items__', // 设置排序组名 draggable: '.ui-element', onEnd: ({ newIndex }) => { items.value[newIndex].order = newIndex // 如果需要保存顺序,可以在这里更新数据状态 } }) } } onMounted(() => { initSortable() }) beforeUnmount(() => { if (activeSortable) { activeSortable.destroy() activeSortable = null } }) </script> <style scoped> .ui-element { border: 1px solid #ccc; padding: 5px; } </style> ``` 在这个例子中,我们创建了一个可拖动的元素列表,并在结束拖动时更新数组中的顺序。记得导入Sortble和相关的CSS样式,以及在适当的时候初始化Sortable
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值