前言
項目整體架構使用的 Vue3 + TypeScript + Ant Design Vue,需求為 table 表格元件支援行資料拖拽排序。本文主要用于記錄。
一、建立 useTableDraggable.ts 檔案,代碼如下。
/**
* useTableDraggable.ts 表格列拖拽
* @param dataSource table資料集合
* @returns customRow 行屬性方法
*/
export default <T>(dataSource: Array<T>) => {
let dragItem: T
let targItem: T
const customRow = (record: T) => {
return {
draggable: true,
ondrag(e: DragEvent) {
dragItem = record
},
ondrop(e: DragEvent) {
targItem = record
},
ondragend(e: DragEvent) {
if (dragItem !== targItem) {
const dragItemIndex = dataSource.indexOf(dragItem);
const targItemIndex = dataSource.indexOf(targItem);
// 解構交換
[dataSource[dragItemIndex], dataSource[targItemIndex]] = [dataSource[targItemIndex], dataSource[dragItemIndex]]
}
},
ondragover(e: DragEvent) {
return false
}
}
}
return {
customRow
}
}
二、使用
<template>
<a-table
bordered
:dataSource="dataSource"
:columns="columns"
:customRow="customRow"
></a-table>
</template>
<script >
import { defineComponent, ref} from 'vue'
import useTableDraggable from '@/hooks/useTableDraggable'
export default defineComponent({
name: 'Table',
setup() {
const dataSource = ref([
{ title: '張三', dataIndex: 'name' },
{ title: '男', dataIndex: 'sex' },
{ title: '18', dataIndex: 'age' }
])
const { customRow } = useTableDraggable(dataSource.value)
return {
dataSource,
columns:[
{ title: "名稱", dataIndex: "title" },
{ title: "鍵值", dataIndex: "dataIndex" }
],
customRow
}
}
})
</script>
參考位址:https://github.com/vueComponent/ant-design-vue/issues/1804