1、安装Sortable.js插件
使用npm install sortable.js --save 或者 yarn add sortable.js
2、还需还要注意是否安装了types/sortablejs插件,如果没有安装还需安装
使用yarn add @types/sortablej 安装或者npm安装视情况而定(不要一会儿npm,一会儿yarn可能会报错,因为两个方法安装的文件路径不同)
3、引入sortable.js
import Sortable from 'sortablejs'
具体详细参数可以看官网:sortable.js中文文档 - itxst.com
4、代码如下
<el-table
@sort-change="handleTableSort"
:data="tableData"
:header-cell-style="{ background: '#F2F3F8', color: '#1D2129' }"
style="width: 100%"
ref="dragTable"
>
<el-table-column width="180">
<template #default>
<el-icon class="move-icon cursor-pointer"><Switch /></el-icon>
</template>
</el-table-column>
<el-table-column label="优先级" property="agreement"> </el-table-column>
<el-table-column label="URL" property="port"> </el-table-column>
<el-table-column label="说明 " property="jumpPort" showOverflowTooltip>
</el-table-column>
<el-table-column label="操作" align="right" width="200">
<template #default="scope">
<el-switch
class="mr-4"
:active-value="1"
:inactive-value="2"
v-model="scope.row.jumpType"
/>
<el-button link type="primary" @click="DelRow(scope.$index, scope.row)">
设置</el-button
>
<el-button link type="danger" @click="DelRow(scope.$index, scope.row)">
删除</el-button
>
</template>
</el-table-column>
</el-table>
import { ref, onMounted, nextTick } from 'vue'
import Sortable from 'sortablejs'
const dragTable = ref()
const initDropTable = () => {
const el = dragTable.value.$el.querySelector('.el-table__body tbody')
Sortable.create(el, {
handle: '.move-icon', //设置指定列作为拖拽
onEnd(evt: any) {
const { newIndex, oldIndex } = evt
console.log(newIndex)
console.log(oldIndex)
const currRow = tableData?.splice(oldIndex, 1)[0]
tableData?.splice(newIndex, 0, currRow)
sortIndex()
}
})
}
const sortIndex = () => {
const array = []
tableData.forEach((e, i) => {
const obj = {
currency_id: e.currency_id,
index: i + 1
}
array.push(obj)
})
}
onMounted(() => {
nextTick(() => {
initDropTable()
})
})