2、最终效果
3、安装sortablejs
npm install sortablejs --save
4、Vue2实现方式
<template>
<el-table
ref="el-table"
:data="tableData"
:class="{'cursor':isCopy,'row_sort':isRowSort,'highlightCurrentRow':highlightCurrentRow,'radioStyle':(table.firstColumn&&table.firstColumn.type==='radio'),'treeProps':isShowTreeStyle}"
v-bind="$attrs"
v-on="$listeners"
:highlight-current-row="highlightCurrentRow"
:border="table.border||isTableBorder"
:span-method="spanMethod||objectSpanMethod"
:cell-class-name="cellClassNameFuc"
@sort-change="soltHandle"
@row-click="rowClick"
@cell-dblclick="cellDblclick"
>
....
</el-table>
</template>
<script>
import Sortable from 'sortablejs'
props: {
table: {
type: Object,
default: () => {
return {}
}
},
isRowSort: {
type: Boolean,
default: false
}
...
},
data() {
return {
tableData: this.table?.data
}
},
watch: {
'table.data': {
handler(val) {
this.tableData = val
},
deep: true
}
},
mounted() {
this.initSort()
},
methods: {
initSort() {
if (!this.isRowSort) return
const el = this.$refs['el-table'].$el.querySelector('.el-table__body-wrapper > table > tbody')
new Sortable(el, {
animation: 150,
onEnd: evt => {
const curRow = this.tableData.splice(evt.oldIndex, 1)[0]
this.tableData.splice(evt.newIndex, 0, curRow)
this.$emit('rowSort', this.tableData)
}
})
}
}
</script>
5、Vue3实现方式
<template>
<div class="t-table" ref="TTableBox">
....
<el-table
ref="TTable"
:data="state.tableData"
:class="{
cursor: isCopy,
row_sort: isRowSort,
highlightCurrentRow: highlightCurrentRow,
radioStyle: table.firstColumn && table.firstColumn.type === 'radio',
}"
v-bind="$attrs"
size="default"
:highlight-current-row="highlightCurrentRow"
:border="table.border || isTableBorder"
@cell-dblclick="cellDblclick"
@row-click="rowClick"
:cell-class-name="cellClassNameFuc"
>
....
</el-table>
</div>
</template>
<script setup lang="ts">
import { computed, ref, watch, useSlots, reactive, onMounted } from 'vue'
import Sortable from 'sortablejs'
const props = defineProps({
table: {
type: Object,
default: () => {
return {}
},
required: true,
},
columns: {
type: Array,
default: () => {
return []
},
},
isRowSort: {
type: Boolean,
default: false,
}
...
})
const state = reactive({
tableData: props.table.data,
...
})
const TTable: any = ref<HTMLElement | null>(null)
const TTableBox: any = ref<HTMLElement | null>(null)
const emits = defineEmits([
'rowSort',
....
])
watch(
() => props.table.data,
(val) => {
state.tableData = val
},
{ deep: true }
)
onMounted(() => {
initSort()
})
const initSort = () => {
if (!props.isRowSort) return
const el = TTableBox.value.querySelector('.el-table__body-wrapper tbody')
Sortable.create(el, {
animation: 150,
onEnd: (evt) => {
const curRow = state.tableData.splice(evt.oldIndex, 1)[0]
state.tableData.splice(evt.newIndex, 0, curRow)
emits('rowSort', state.tableData)
},
})
}
</script>
注意事项,el-table需要配置row-key
且保持唯一性,不然会出现排序不对的情况
7、组件地址
Vue3组件地址
Vue2组件地址
8、相关文章
Vue2基于ElementUi再次封装基础组件文档
vue3+ts基于Element-plus再次封装基础组件文档