什么是sortable
Sortable.js是一款优秀的js拖拽库,支持ie9及以上版本ie浏览器和现代浏览器,也可以运行在移动触摸设备中。不依赖jQuery。支持 Meteor、AngularJS、React、Vue、Knockout框架和任何CSS库,如Bootstrap、Element UI。你可以用来拖拽div、table等元素。
sortable.js中文文档.
需求场景
需要对表格数据进行拖拽排序
安装
npm install sortablejs --save
引入
import Sortable from 'sortablejs'
使用
我这里使用的vue + element
1.在 el-tabl 内添加ref,方便我们获取节点
<el-table ref="dragTable" :data="listdata" border style="width: 100%">
2.编写拖拽的方法
setSort() {
const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]// 获取 tbody 节点
this.sortable = Sortable.create(el, {// 初始化顺便设置配置
ghostClass: 'sortable-ghost', // 停靠位置样式(要拖动的元素的样式,给拖动的元素添加类名,自己再css中设置样式)
setData: function(dataTransfer, dragEl) { // 避免 Firefox 的bug
dataTransfer.setData('Text', dragEl.textContent)
},
// 拖动结束的回调
onEnd: evt => {
let oldList = this.listdata[evt.oldIndex];// oldIndex旧的排序
let newList = this.listdata[evt.newIndex];// newIndex新的排序
// 需要传递的参数
this.sort = {
currId: oldList.id,
newId: newList.id,
currSort: oldList.sort,
newSort: newList.sort
}
this.$emit('sortList', this.sort)// 触发父元素的发送请求,顺便把参数传过去
}
})
}
3.监听排序变化,重新渲染
watch: {
listdata(){
console.log('ok')
this.oldList = this.listdata.map(v => v.id)
this.newList = this.oldList.slice()
this.$nextTick(() => {
this.setSort()
})
}
}
4.最后附上注册的data
data(){
return {
sortable: null,
oldList: [],
newList: [],
sort: {
currId: 0,
newId: 0,
currSort: 0,
newSort: 0
}
}
},
结尾
拖拽排序的功能就完成了,但是需要注意:每个后端给的接口都不一样,你需要根据接口的返回参数以及需要的参数进行修改。本篇文章只能用于借鉴、