current position:Home>Vue + Element tree form implement drag-and-drop sequence

Vue + Element tree form implement drag-and-drop sequence

2022-08-06 19:02:53front-end anonymous worker

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第5天,点击查看活动详情 >>

Today, I will share with you the drag-and-drop sorting of the tree table,There are not many tutorials on sorting tree tables,There may still be problems,I will explain it to you in detail here,If you have such a need or find it useful,Please give a follow or favorite it,It is convenient for later review and use.

安装sortablejs

npm install sortablejs --save
复制代码

在需要的页面引入

import Sortable from 'sortablejs'
复制代码

form plusrow-key="id"

<el-table ref="table" row-key="id" :data="tableData" style="width: 100%">
  <el-table-column prop="date" label="日期" width="180"></el-table-column>
  <el-table-column prop="name" label="姓名" width="180"></el-table-column>
</el-table>
复制代码

Tree table sorting(树结构)

Tree table sorting implementation principle:Convert the tree structure to a list and then drag and drop,If not converted,The position of the drag is wrong,就出错了

data() {
  return {
    tableData: [
    	{
    		id: 1,
    		name: 'AAA',
    		level: 1,
    		children: [
    			{
    				id: 2,
		    		name: 'A-1',
		    		level: 2
    			}
    		]
    	},
    	{
    		id: 3,
    		name: 'BBB',
    		level: 1,
    		children: []
    	}
    ],
    activeRows: [] // Data converted to a list
  }
},
mounted () {
	this.rowDrop()
},
methods: {
 	// Convert tree data to tile data
	treeToTile (treeData, childKey = 'children') {
      const arr = []
      const expanded = data => {
        if (data && data.length > 0) {
          data.filter(d => d).forEach(e => {
            arr.push(e)
            expanded(e[childKey] || [])
          })
        }
      }
      expanded(treeData)
      return arr
    },
	rowDrop() {
      const tbody = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      Sortable.create(tbody , {
      	animation: 300,
      	onMove: () => {
      		this.activeRows = this.treeToTile(this.tableData) // Convert the tree structure to a list and then drag and drop
      	},
      	onEnd: e => {
	       	//e.oldIndex为拖动一行原来的位置,e.newIndex为拖动后新的位置
	       	if (e.oldIndex !== e.newIndex) { // Add conditions and restrictions according to your own project needs
	       		const oldRow = this.activeRows[e.oldIndex] // The element to move
	       		const newRow = this.activeRows[e.newIndex] // 新的元素
	       		// Request interface ordering,Fill in the parameters according to the backend requirements
		
	       	}
	   	 } 
      })
   }
}

复制代码

这里就使用了2个方法,还有其它方法,根据自己需求来使用

方法介绍
onAdd: function (evt) { // 拖拽时候添加有新的节点的时候发生该事件
	console.log('onAdd.foo:', [evt.item, evt.from])
},
onUpdate: function (evt) { // 拖拽更新节点位置发生该事件
  	console.log('onUpdate.foo:', [evt.item, evt.from])
},
onRemove: function (evt) { // 删除拖拽节点的时候促发该事件
 	 console.log('onRemove.foo:', [evt.item, evt.from])
},
onStart: function (evt) { // 开始拖拽出发该函数
 	 console.log('onStart.foo:', [evt.item, evt.from])
},
onSort: function (evt) { // 发生排序发生该事件
  	console.log('onUpdate.foo:', [evt.item, evt.from])
},
onEnd ({ newIndex, oldIndex }) { // 结束拖拽
 	 let currRow = _this.tableData.splice(oldIndex, 1)[0]
 	 _this.tableData.splice(newIndex, 0, currRow)
}
复制代码

注意点

1.如果你的onEndMethods are not arrow functions,如下面这样,It needs to be defined abovethis指向,不然会报错

const _this = this
Sortable.create(tbody , {
	onEnd ({ oldIndex, newIndex }) {
	
	}
})
复制代码

2.Add drag and drop method,Need to wait for the table data to be obtained,Otherwise it may be emptytbody ,Drag and drop does not work. 可以在awaitAfter the table data is obtained,在调用rowDrop方法

3.If the table is refreshed,Will cause the drag to fail,The drag and drop method needs to be re-addedthis.rowDrop()

4.If the table is refreshed it will cause the page to refresh,The scroll bar is not where it was before,The page needs to be re-scrolled,体验效果不好.The solution is to record the scroll bar position,Refresh the page after dragging and scrolling to the current position automatically,The next article will explain recording scroll position,Please go to my homepage to view

结语

These are some of the problems bloggers have encountered in the project,If you have problems in use,Please say it in the comments section

copyright notice
author[front-end anonymous worker],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/218/202208061858275580.html

Random recommended