1、首先需要下载sortablejs第三方包
2、在需要排序的页面文件里引入:
import Sortable from 'sortablejs'
data() {
return {
apiObjDrag: [],
productList:[],整个列表数据项
}
},
methods:{
//行-拖拽
rowDrop() {
const tbody = document.querySelector('.el-table__body-wrapper tbody')
const _this = this
Sortable.create(tbody, {
onEnd({ newIndex, oldIndex }) {
const currRow = _this.productList.splice(oldIndex, 1)[0]
_this.productList.splice(newIndex, 0, currRow)
// 拖动后获取newIdex
let arr = Array.from(_this.productList)
_this.apiObjDrag = arr
_this.sortPro(_this.apiObjDrag)
},
})
},
sortPro(proList) {
this.http.post('productListSort', proList).then((res) => {
if (res) {
this.fetchData() //刷新页面功能
}
})
},
3、还可通过点击列表上下箭头进行排序
<el-table-column
label="序号"
type="index"
:index="indexMethod"
width="80"
align="center"
<template slot-scope="scope">
<i
class="el-icon-caret-top"
style="cursor: pointer;"
@click="sortProUp(scope.row)"
></i>
<span>{{ scope.$index + 1 }}</span>
<i
class="el-icon-caret-bottom"
style="cursor: pointer;"
@click="sortProDown(scope.row)"
></i>
</template>
</el-table-column>
// 下调序号
sortProDown(productObj) {
const proList = this.productList
const _index = _.indexOf(proList, productObj)
if (_index < proList.length - 1) {
const temp = proList[_index]
proList[_index] = proList[_index + 1]
proList[_index + 1] = temp
this.sortPro(proList)
}
},
//上调
sortProUp(productObj) {
const proList = this.productList
const _index = _.indexOf(proList, productObj)
if (_index > 0) {
const temp = proList[_index]
proList[_index] = proList[_index - 1]
proList[_index - 1] = temp
this.sortPro(proList)
}