這回想封裝 Element Plus 表格的 Group Column 和 Group Row,讓其更能符合業務需求,進而減少撰寫重複的程式碼。這邊筆記下過程。
內容
1. 外部定義 arraySpanMethod 和 objectSpanMethod 的執行內容
2. 透過一個 boolean 來確定要傳入的是哪一種方法
3. 定義相關的 TypeScript 型別
程式碼範例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<el-table | |
v-loading="loading" | |
:data="props.list" | |
style="width: 100%" | |
:highlight-current-row="highlightCurrentRow" | |
:span-method="spanMethod" | |
> | |
<script setup lang="ts"> | |
import { PropType, reactive, toRefs } from 'vue' | |
const props = defineProps({ | |
loading: { | |
required: false, | |
type: Boolean, | |
default: false | |
}, | |
list: { | |
required: true, | |
type: Array as PropType<Record<string, any>[]> | |
}, | |
settings: { | |
required: true, | |
type: Object as PropType<Record<string, any>> | |
} | |
}) | |
const defaultSettings = reactive({ | |
spanMethod: props.settings.mergeRowOrColumn === 'row' | |
? props.settings.arraySpanMethod || undefined | |
: props.settings.mergeRowOrColumn === 'column' ? props.settings.objectSpanMethod || undefined : undefined | |
}) | |
const { spanMethod } = toRefs(defaultSettings) | |
</script> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { TableColumnCtx } from 'element-plus/es/components/table/src/table-column/defaults' | |
export interface SpanMethodProps<T extends Record<string, any>> { | |
row: T | |
column: TableColumnCtx<T> | |
rowIndex: number | |
columnIndex: number | |
} | |
export interface TableSettings { | |
mergeRowOrColumn?: 'row'|'column', | |
arraySpanMethod?: <T>({ row, column, rowIndex, columnIndex }:SpanMethodProps<T>) => number[] | undefined, | |
objectSpanMethod?: <T>({ row, column, rowIndex, columnIndex }:SpanMethodProps<T>) => { | |
rowspan: number; | |
colspan: number; | |
} | undefined | |
} |