Vue element table realizes drag sorting

Recently, the table list in the project needs to be dragged and sorted. The sortable.js plug-in is used, which is an excellent js drag-and-drop library and does not rely on jQuery. Support Meteor, AngularJS, React, Vue, Knockout framework and any CSS library, such as Bootstrap, Element UI. It can be used to drag and drop elements such as div and table.

installation:

npm install sortablejs

Then introduce this plugin in js:

import Sortable from "sortablejs"

Add row-key and ref to the table:

<el-table row-key="tableData" ref="singleTable" :data="list" style="width: 100%;">

注:row-key 写不正确可能会出现一些BUG,唯一就可以

Implementation:

mounted(){
	this.dragSort();
},
methods:{
	//表格拖动排序
	dragSort() {
		const el = this.$refs.singleTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
		this.sortable = Sortable.create(el, {
			onEnd: e => {	//onEnd是结束拖拽时触发,onUpdate是列表内元素顺序更新的时候触发,更多请看文末配置项
				//e.oldIndex为拖动一行原来的位置,e.newIndex为拖动后新的位置
				const targetRow = this.tableData.splice(e.oldIndex, 1)[0];
				this.tableData.splice(e.newIndex, 0, targetRow);
				let dragId = this.tableData[e.newIndex].id;//拖动行的id
				let oneId,twoId
				//拖动行的前一行
				if( this.tableData[e.newIndex-1]){
					oneId = this.tableData[e.newIndex-1].id;
				}else {
					oneId = ""
				}
				//拖动行的后一行
				if( this.tableData[e.newIndex+1]){
					twoId = this.tableData[e.newIndex+1].id;}
				else {
					twoId = ""
				}
				console.log("拖动行:"+dragId);
				console.log("前一行:"+oneId);
				console.log("后一行:"+twoId);
				//然后就可以发送请求了......
			}
		})
	}
					
}

Configuration items:

http://www.sortablejs.com/options.html You can change the sorting animation time, customize the shadow style, specify drag elements, multiple lists in the same group, etc.

other:

如果使用的不是表格,而是以 v-for 的形式生成的动态数据,并且出现了排序混乱等BUG,可以尝试把数据源换成原本数据源的副本看看,注意不是基本类型要用深拷贝

Guess you like

Origin blog.csdn.net/weixin_45879810/article/details/111028919