如果使用element Table排序看另一篇 vue使用sortablejs结合element Table实现拖拽
<template>
<div class="table">
<div class="list">
<div class="item" v-for="item in tableData" :key="item.id">{{item.name}}</div>
</div>
</div>
</template>
<script>
import Sortable from "sortablejs";
export default {
data() {
return {
tableData: [
{
id: 1,
date: "2016-05-02",
name: "刘日天1号",
address: "上海市普陀区金沙江路 1518 弄",
},
{
id: 2,
date: "2016-05-04",
name: "刘日天2号",
address: "上海市普陀区金沙江路 1517 弄",
},
{
id: 3,
date: "2016-05-01",
name: "刘日天3号",
address: "上海市普陀区金沙江路 1519 弄",
},
{
id: 4,
date: "2016-05-03",
name: "刘日天4号",
address: "上海市普陀区金沙江路 1516 弄",
},
],
oldIndex: null, // 初始位置
newIndex: null, // 目标位置
};
},
mounted() {
this.rowDrop();
},
methods: {
rowDrop() {
const tbody = document.querySelector(".list");
const _this = this;
Sortable.create(tbody, {
animation: 1000, //动画
draggable: ".item", // 允许拖拽的项目类名
// 因为拖拽过程中不尽兴位置调整,所以就要记录拖拽行初始位置以及目标位置
// 拖拽中 回调函数
onMove(customEvent) {
// 禁止在拖拽过程中交换位置
// 可将初始位置及目标位置进行记录
// _this.oldIndex = customEvent.dragged.rowIndex; // 初始位置
// _this.newIndex = customEvent.related.rowIndex; // 目标位置
// return false; // 不进行交换
// 返回值有三个
// return false; — for cancel
// return -1; // — insert before target
// return 1; // — insert after target
},
onEnd(evt) {
console.log(evt);
// 在拖拽结束后,获取初始及目标位置
// const { newIndex, oldIndex } = _this;
const newIndex = evt.newIndex
const oldIndex = evt.oldIndex
const currRow = _this.tableData.splice(oldIndex, 1)[0];
console.log(currRow);
_this.tableData.splice(newIndex, 0, currRow);
// 此时记得把交换后的数据,发送给后端进行记录
// this.$axios({url,method,data}).......
// 拖拽完成,初始位置及目标位置重置
_this.newIndex = null;
_this.oldIndex = null;
},
});
},
},
};
</script>
<style scoped>
.table {
padding: 20px;
}
.handle_move {
cursor: move;
width: 100px;
}
.list{
width: 550px;
display: flex;
flex-wrap: wrap;
}
.list .item{
width: 130px;
height: 130px;
border: #000 solid 1px;
flex-shrink: 0;
margin: 20px;
background-color: pink;
}
</style>