有时
vue
项目中,列表重新拖拽排序,这里就简单讲下怎么实现…
- 首先需要下载依赖
npm install sortablejs -S
Sortable.js是一款优秀的js拖拽库,支持ie9及以上版本ie浏览器和现代浏览器,也可以运行在移动触摸设备中。
-
在需要拖拽的页面里引用
import Sortable from "sortablejs"
-
在代码table组件里加上ref属性获取元素
//这里只展示部分代码 主要是ref
<a-table :columns="columns" :data-source="data" ref="dragTable">
</a-table>
- 在mounted里去调这个拖拽的方法
mounted() {
this.rowDrop();
},
/**列表支持拖拽排序**/
methods:{
rowDrop() {
const el = this.$refs.dragTable.$el.querySelectorAll("tbody")[0];//获取table里元素
this.sortable = Sortable.create(el, {
ghostClass: "blue-background-class", //选中元素插入属性
sort: true,//是否允许元素内部排序,
handle: ".ant-table-row",
animation: 150, //定义排序动画的时间ms
onEnd: ({ newIndex, oldIndex }) => {
if (oldIndex == newIndex) return;
const targetRow =
this.scenceData.splice(oldIndex, 1)[0]; //选中的目标源对象
this.scenceData.splice(newIndex, 0, targetRow);
let replacedataRow = this.newScenceData.filter(
(val, index) => index == newIndex
)[0]; //拖拽之前,数据原来的位置的数据对象
//根据上面获取的数据 根据后端的接口,传相应的数据
//这里是调接口====,根据自己需求来写
},
});
},
}
- 以上就可以实现table拖拽排序了