vue+Element-ui实现表格拖拽排序功能

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)
}

posted @   三猫拉拉  阅读(1173)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示