vue3+element+sortablejs实现table表格 行列动态拖拽

文章介绍了如何在Vue3项目中使用ElementUI和SortableJS库来实现表格行的动态拖拽排序功能。首先需要安装SortableJS依赖,然后在组件中导入并初始化SortableJS。在模板中定义两个表格,通过SortableJS的创建实例和配置项实现拖放行为。同时,文章还提到如何扩展功能,判断拖动的行是否能放置到新的位置,基于特定条件进行排序更新。

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

1.第一步我们要安装sortablejs依赖

博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片.

npm install sortablejs --save

或者

pnpm install sortablejs --save

或者

yarn add sortablejs --save

2.在我们需要的组件中引入

import Sortable from 'sortablejs'

3.完整代码

<template>
	<div class="one dp-flex">
		<div style="flex: 1" class="ones">
			<el-table :data="tableData" class="tableOne">
				<el-table-column
					v-for="(column, index) in tableColumns"
					:key="index"
					:label="column.label"
					:prop="column.prop"
					:index="index"
					:row-index="null"
					:sortable="true"
					@sort-change="handleSortChange"
				></el-table-column>
			</el-table>
		</div>
		<div style="flex: 1; margin-left: 30px" class="twos">
			<el-table :data="tableData" class="tableTwo">
				<el-table-column
					v-for="(column, index) in tableColumns"
					:key="index"
					:label="column.label"
					:prop="column.prop"
					:index="index"
					:row-index="null"
					:sortable="true"
					@sort-change="handleSortChange"
				></el-table-column>
			</el-table>
		</div>
	</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import Sortable from 'sortablejs';

let tableData = ref([
	{
		id: 1,
		name: '1',
		age: 18,
	},
	{
		id: 2,
		name: '2',
		age: 11,
	},
	{
		id: 3,
		name: '3',
		age: 13,
	},
]);
let tableColumns = ref([
	{ label: 'id', prop: 'id' },
	{ label: 'name', prop: 'name' },
	{ label: 'age', prop: 'age' },
]);
onMounted(() => {
	// new Sortable(example1, {
	// 	animation: 150,
	// 	ghostClass: 'blue-background-class',
	// });
	// const table = document.querySelector('.el-table__body-wrapper');
	const table1 = document.querySelector(`.ones .${'tableOne'} .el-table__body-wrapper tbody`);
	const table2 = document.querySelector(`.twos .${'tableTwo'} .el-table__body-wrapper tbody`);

	Sortable.create(table1, {
		group: {
			name: 'shared',
			pull: 'clone',
			put: false, // 不允许拖拽进这个列表
		},
		animation: 150,
		sort: false, // 设为false,禁止sort
	});
	Sortable.create(table2, {
		group: 'shared',
		animation: 150,
		onEnd: handleDragEnds,
	});
});
function handleSortChange({ oldIndex, newIndex, index, rowIndex }) {
	console.log('排序');

	// 处理列拖拽排序
	if (rowIndex === null) {
		// 处理表头列拖拽排序
		// 更新tableColumns的顺序
	} else {
		// 处理表格行列拖拽排序
		// 更新tableData的顺序
	}
}
function handleDragEnd() {
	// 拖拽结束后的处理
	console.log('拖拽结束后的处理');
}
function handleDragEnds() {
	// 拖拽结束后的处理
	console.log('拖拽结束后的处理');
}
</script>

4.效果

在这里插入图片描述

5.扩展:判断要拖动的行能不能拖动并放置到新位置

	const table2 = document.querySelector(`.AA  .${'right'} .el-table__body-wrapper tbody`);
	Sortable.create(table2, {
		group: 'shared',
		animation: 150,
		sort: true,
		onEnd: function (evt: any) {
			//拖拽结束发生该事件
			const movedItem = zongitemright.value[evt.oldIndex]; //拖动行数据

			const prevItem = zongitemright.value[evt.newIndex - 1]; //目标行上一行
			const nextItem = zongitemright.value[evt.newIndex]; //目标行下一行
			// 判断条件满足不满足(上下的fdtlvalue判断)
			if ((!prevItem || prevItem.fdtlvalue <= movedItem.fdtlvalue) && (!nextItem || movedItem.fdtlvalue <= nextItem.fdtlvalue)) {
				const movedItems = zongitemright.value.splice(evt.oldIndex, 1)[0]; //先删除原位置的拖动行
				zongitemright.value.splice(evt.newIndex, 0, movedItems);
			}
			let newArray = zongitemright.value.slice(0);
			zongitemright.value = [];
			nextTick(() => {
				zongitemright.value = newArray;
			});
		},
	});
Vue3Element Plus框架下,结合Sortable库可以轻松实现表格拖拽排序功能。首先,你需要安装相关的依赖,包括`element-plus`、`vue-sortablejs`等。以下是一个简单的步骤说明: 1. **安装依赖**: - 使用npm或yarn安装Element Plus:`npm install element-plus` - 安装Sortable库:`npm install sortablejs` 2. **引入组件和样式**: 在项目文件中导入Element Plus的Table组件以及Sortable库: ```javascript import { Table } from &#39;element-plus&#39;; import Sortable from &#39;sortablejs&#39;; ``` 3. **创建数据源**: 初始化一个包含可排序数组的数据结构,比如: ```javascript const dataSource = [ { id: 1, name: &#39;Item 1&#39;, // 添加其他属性... }, ... // 其他数据项 ]; ``` 4. **绑定Sortable到表头**: 在Table的列定义中,将Sortable应用到需要排序的那一列: ```html <template> <Table :data="dataSource" ref="tableRef"> <TableHeaderRow :columns="columns"> <!-- 使用sortablejs处理的列 --> <th v-for="(column, index) in columns" :key="index" @sort-change="handleSortChange(column)"> {{ column.label }} <span slot="scope" class="cursor-pointer">{{ sortOrders[column.prop] }}</span> </th> </TableHeaderRow> <!-- ...其他Table内容... --> </Table> </template> <script> export default { data() { return { columns: [ { prop: &#39;name&#39;, label: &#39;Name&#39;, sortable: true }, {/* ...其他列... */} ], sortOrders: {}, // 存储排序信息 }; }, methods: { handleSortChange(column) { this.sortOrders[column.prop] = column.order; // 更新排序后的数据源,这里通常会涉及数据库操作或本地状态更新 this.dataSource = this.dataSource.sort((a, b) => { if (column.order === &#39;asc&#39;) { return a[column.prop].localeCompare(b[column.prop]); } else { return b[column.prop].localeCompare(a[column.prop]); } }); }, }, }; </script> ``` 5. **初始化Sortable**: 在`mounted()`钩子中,初始化Sortable实例并设置回调函数: ```javascript mounted() { const tableHeader = this.$refs.tableRef.head; if (tableHeader) { Sortable(tableHeader.querySelector(&#39;th.cursor-pointer&#39;), { group: &#39;__TABLE_SORT__&#39;, // 设置组名防止冲突 onEnd: ({ newIndex }) => { // 需要根据newIndex更新数据库或其他地方的排序顺序 this.handleSortChange({ prop: this.columns[newIndex].prop, order: newIndex > this.columns.length / 2 ? &#39;desc&#39; : &#39;asc&#39; }); }, }); } }, ``` 6. **注意事项**: - 确保在实际项目中处理好状态管理和数据同步,例如Vuex或自定义事件系统。 - 根据需求调整排序图标或显示方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值