Files
admin-web/src/shared/components/DataTable.vue
T

397 lines
18 KiB
Vue
Raw Normal View History

<script lang="ts">
export interface DataTableColumn {
key?: string | number
label?: string
prop?: string
property?: string
columnKey?: string
slotName?: string
headerSlotName?: string
2026-08-06 19:03:13 +08:00
hideable?: boolean
movable?: boolean
defaultVisible?: boolean
[attribute: string]: unknown
}
export type PaginationItem = number | 'ellipsis-start' | 'ellipsis-end'
export function normalizePageSizes(values: readonly number[]) {
const sizes = values
.filter((value) => Number.isFinite(value))
.map((value) => Math.trunc(value))
.filter((value) => value > 0)
const uniqueSizes = [...new Set(sizes)]
return uniqueSizes.length > 0 ? uniqueSizes : [10]
}
export function normalizePage(value: number, pageCount: number) {
const maximum = Number.isFinite(pageCount) && pageCount > 0 ? Math.trunc(pageCount) : 1
if (!Number.isFinite(value)) return 1
return Math.min(Math.max(Math.trunc(value), 1), maximum)
}
2026-08-21 17:20:40 +08:00
export function normalizeTotal(value: unknown) {
const numericValue = typeof value === 'string' && value.trim() !== '' ? Number(value) : value
return typeof numericValue === 'number' && Number.isFinite(numericValue) && numericValue > 0
? Math.trunc(numericValue)
: 0
}
export function createPaginationItems(page: number, pageCount: number): PaginationItem[] {
if (pageCount <= 0) return []
if (pageCount <= 7) return Array.from({ length: pageCount }, (_, index) => index + 1)
if (page <= 4) return [1, 2, 3, 4, 5, 'ellipsis-end', pageCount]
if (page >= pageCount - 3) {
return [1, 'ellipsis-start', pageCount - 4, pageCount - 3, pageCount - 2, pageCount - 1, pageCount]
}
return [1, 'ellipsis-start', page - 1, page, page + 1, 'ellipsis-end', pageCount]
}
</script>
<script setup lang="ts">
2026-08-06 19:03:13 +08:00
import { computed, inject, nextTick, ref, useSlots, watch } from 'vue'
import { ChevronLeft, ChevronRight, Settings2 } from '@lucide/vue'
import LayoutPreferenceList, { type LayoutPreferenceItem } from './LayoutPreferenceList.vue'
import {
UI_PREFERENCE_SCOPE,
readLayoutPreference,
removeLayoutPreference,
writeLayoutPreference,
type LayoutPreferenceSnapshot,
} from '@/shared/utils/uiLayoutPreference'
defineOptions({ inheritAttrs: false })
const props = withDefaults(defineProps<{
data: object[]
columns: DataTableColumn[]
loading?: boolean
emptyText?: string
2026-08-21 17:20:40 +08:00
total?: number | string
pageSizes?: number[]
2026-08-25 22:08:59 +08:00
maxHeight?: string | number
2026-08-06 19:03:13 +08:00
preferenceKey?: string
2026-08-11 20:39:34 +08:00
columnSettingsMode?: 'auto' | 'show' | 'hide'
2026-08-12 18:50:03 +08:00
border?: boolean
stripe?: boolean
}>(), {
loading: false,
emptyText: '暂无数据',
total: undefined,
pageSizes: () => [10, 20, 50, 100],
2026-08-25 22:08:59 +08:00
maxHeight: 'calc(100vh - 300px)',
2026-08-11 20:39:34 +08:00
columnSettingsMode: 'auto',
2026-08-12 18:50:03 +08:00
border: true,
stripe: true,
})
const page = defineModel<number>('page', { default: 1 })
const pageSize = defineModel<number>('pageSize', { default: 10 })
const slots = useSlots()
2026-08-06 19:03:13 +08:00
const preferenceScope = inject(UI_PREFERENCE_SCOPE, computed(() => 'anonymous'))
const preference = ref<LayoutPreferenceSnapshot>({ version: 1, order: [], hidden: [] })
const tableRef = ref<{ doLayout: () => void }>()
function columnId(column: DataTableColumn) {
const value = column.key ?? column.columnKey ?? column.prop ?? column.property
return value === undefined || value === null || value === '' ? undefined : String(value)
}
function systemColumn(column: DataTableColumn) {
const id = columnId(column)
return id === 'actions'
|| column.fixed === 'left'
|| ['selection', 'expand', 'index'].includes(String(column.type || ''))
}
function columnMovable(column: DataTableColumn) {
return column.movable ?? !systemColumn(column)
}
function columnHideable(column: DataTableColumn) {
return column.hideable ?? !systemColumn(column)
}
const configurableColumns = computed(() => props.columns.filter((column) => columnId(column)))
const columnKeys = computed(() => configurableColumns.value.map((column) => columnId(column) as string))
2026-08-11 20:39:34 +08:00
const columnSettingsVisible = computed(() => (
props.columnSettingsMode === 'auto'
? configurableColumns.value.filter(columnHideable).length > 4
: props.columnSettingsMode === 'show'
))
const preferenceEnabled = computed(() => Boolean(props.preferenceKey && columnSettingsVisible.value))
2026-08-06 19:03:13 +08:00
2026-08-06 19:18:48 +08:00
function anchorSystemColumns(order: readonly string[]) {
const columnsByKey = new Map(configurableColumns.value.map((column) => [columnId(column) as string, column]))
const movableKeys = order.filter((key) => {
const column = columnsByKey.get(key)
return column && columnMovable(column)
})
let movableIndex = 0
return configurableColumns.value.map((column) => (
columnMovable(column) ? movableKeys[movableIndex++] : columnId(column) as string
))
}
2026-08-06 19:03:13 +08:00
function applyPreference() {
const defaultHidden = configurableColumns.value.flatMap((column) => column.defaultVisible === false ? [columnId(column) as string] : [])
2026-08-06 19:18:48 +08:00
const snapshot = readLayoutPreference(
2026-08-06 19:03:13 +08:00
'table',
preferenceScope.value,
props.preferenceKey || '',
columnKeys.value,
defaultHidden,
)
2026-08-06 19:18:48 +08:00
preference.value = { ...snapshot, order: anchorSystemColumns(snapshot.order) }
2026-08-06 19:03:13 +08:00
}
watch(
[preferenceScope, () => props.preferenceKey, () => columnKeys.value.join('\u0000')],
applyPreference,
{ immediate: true },
)
const orderedColumns = computed(() => {
if (!preferenceEnabled.value) return props.columns
const columnsByKey = new Map(configurableColumns.value.map((column) => [columnId(column) as string, column]))
return preference.value.order.flatMap((key) => {
const column = columnsByKey.get(key)
return column ? [column] : []
})
})
const visibleColumns = computed(() => orderedColumns.value.filter((column) => {
const id = columnId(column)
2026-08-11 20:39:34 +08:00
return !preferenceEnabled.value || !id || !columnHideable(column) || !preference.value.hidden.includes(id)
2026-08-06 19:03:13 +08:00
}))
const visibleHideableCount = computed(() => visibleColumns.value.filter(columnHideable).length)
const preferenceItems = computed<LayoutPreferenceItem[]>(() => orderedColumns.value.flatMap((column) => {
const key = columnId(column)
if (!key) return []
const visible = !preference.value.hidden.includes(key)
const hideable = columnHideable(column)
return [{
key,
label: column.label || (String(column.type || '') === 'selection' ? '选择' : key),
visible,
hideable,
movable: columnMovable(column),
hideDisabled: visible && hideable && visibleHideableCount.value <= 1,
}]
}))
function persistPreference(order: string[], hidden = preference.value.hidden) {
preference.value = { version: 1, order, hidden }
writeLayoutPreference('table', preferenceScope.value, props.preferenceKey || '', preference.value)
}
function moveColumn(key: string, targetIndex: number) {
const movableKeys = orderedColumns.value.filter(columnMovable).map((column) => columnId(column) as string)
const currentIndex = movableKeys.indexOf(key)
if (currentIndex < 0) return
movableKeys.splice(currentIndex, 1)
movableKeys.splice(Math.min(Math.max(targetIndex, 0), movableKeys.length), 0, key)
const movableSet = new Set(movableKeys)
let nextMovableIndex = 0
2026-08-06 19:18:48 +08:00
const order = orderedColumns.value.map((column) => {
const id = columnId(column) as string
return movableSet.has(id) ? movableKeys[nextMovableIndex++] : id
})
2026-08-06 19:03:13 +08:00
persistPreference(order)
}
function setColumnVisibility(key: string, visible: boolean) {
const column = configurableColumns.value.find((candidate) => columnId(candidate) === key)
if (!column || !columnHideable(column)) return
if (!visible && visibleHideableCount.value <= 1) return
const hidden = visible
? preference.value.hidden.filter((id) => id !== key)
: [...new Set([...preference.value.hidden, key])]
persistPreference(preference.value.order, hidden)
}
function resetPreference() {
removeLayoutPreference('table', preferenceScope.value, props.preferenceKey || '')
applyPreference()
}
watch(visibleColumns, () => {
void nextTick(() => tableRef.value?.doLayout())
})
2026-08-21 17:20:40 +08:00
const normalizedTotal = computed(() => normalizeTotal(props.total))
const normalizedPageSizes = computed(() => normalizePageSizes(props.pageSizes))
const effectivePageSize = computed(() => (
normalizedPageSizes.value.includes(pageSize.value) ? pageSize.value : normalizedPageSizes.value[0]
))
const pageCount = computed(() => (
normalizedTotal.value === 0 ? 0 : Math.ceil(normalizedTotal.value / effectivePageSize.value)
))
const currentPage = computed(() => normalizePage(page.value, pageCount.value))
const paginationItems = computed(() => createPaginationItems(currentPage.value, pageCount.value))
watch([pageSize, normalizedPageSizes], ([value, sizes]) => {
const integerValue = Number.isFinite(value) ? Math.trunc(value) : sizes[0]
const nextValue = sizes.includes(integerValue) ? integerValue : sizes[0]
if (value === nextValue) return
pageSize.value = nextValue
page.value = 1
}, { immediate: true })
watch([page, pageCount], ([value, count]) => {
const nextValue = normalizePage(value, count)
if (value !== nextValue) page.value = nextValue
}, { immediate: true })
2026-08-06 19:03:13 +08:00
function columnAttrs({ key, slotName, headerSlotName, hideable, movable, defaultVisible, ...attrs }: DataTableColumn) {
2026-08-12 17:45:49 +08:00
const hasDataProperty = attrs.prop !== undefined || attrs.property !== undefined
const isSpecialColumn = slotName || ['selection', 'expand', 'index'].includes(String(attrs.type || ''))
if (hasDataProperty || isSpecialColumn || key === undefined || key === null || key === '') return attrs
const label = String(attrs.label || '')
return {
...attrs,
prop: String(key),
formatter: attrs.formatter || ((_row: unknown, _column: unknown, value: unknown) => {
if (value === null || value === undefined || value === '') return '—'
if (typeof value === 'number' && /CNY|金额|应收|应付|已收|已付|未收|待收|待付|开账/.test(label)) return value.toFixed(2)
return String(value)
}),
}
}
function columnRenderKey(column: DataTableColumn, index: number) {
return String(column.key ?? column.columnKey ?? column.prop ?? column.property ?? index)
}
function hasSlot(name?: string) {
return Boolean(name && slots[name])
}
function updatePageSize(value: number) {
const nextValue = normalizedPageSizes.value.includes(value) ? value : normalizedPageSizes.value[0]
if (nextValue === pageSize.value) return
pageSize.value = nextValue
page.value = 1
}
function setPage(value: number) {
page.value = normalizePage(value, pageCount.value)
}
</script>
<template>
<div class="data-table">
2026-08-10 16:24:54 +08:00
<div
v-if="$slots['toolbar-start'] || $slots['toolbar-actions'] || preferenceEnabled || $slots['toolbar-end']"
class="data-table__toolbar"
:class="{ 'is-compact': !$slots['toolbar-start'] }"
>
<div v-if="$slots['toolbar-start']" class="data-table__toolbar-start"><slot name="toolbar-start" /></div>
2026-08-10 17:42:17 +08:00
<div class="data-table__toolbar-actions" :class="{ 'has-business-actions': $slots['toolbar-actions'] }">
2026-08-06 20:14:56 +08:00
<div v-if="$slots['toolbar-actions']" class="data-table__business-actions"><slot name="toolbar-actions" /></div>
2026-08-10 17:42:17 +08:00
<div v-if="preferenceEnabled || $slots['toolbar-end']" class="data-table__utility-actions">
<el-popover v-if="preferenceEnabled" placement="bottom-end" :width="340" trigger="click" popper-class="cc-layout-preference-popper">
<template #reference>
<el-button aria-label="列设置" title="列设置"><Settings2 :size="16" /></el-button>
</template>
<LayoutPreferenceList
:items="preferenceItems"
allow-visibility
@move="moveColumn"
@visibility="setColumnVisibility"
@reset="resetPreference"
/>
</el-popover>
<div v-if="$slots['toolbar-end']" class="data-table__toolbar-end"><slot name="toolbar-end" /></div>
</div>
2026-08-06 20:14:56 +08:00
</div>
2026-08-06 19:03:13 +08:00
</div>
2026-08-25 22:08:59 +08:00
<el-table ref="tableRef" v-bind="$attrs" v-loading="loading" :data="data" :empty-text="emptyText" :border="border" :stripe="stripe" :max-height="maxHeight" :aria-busy="loading">
<el-table-column
2026-08-06 19:03:13 +08:00
v-for="(column, index) in visibleColumns"
:key="columnRenderKey(column, index)"
v-bind="columnAttrs(column)"
>
<template v-if="hasSlot(column.headerSlotName)" #header="scope">
<slot :name="column.headerSlotName" v-bind="scope" />
</template>
<template v-if="hasSlot(column.slotName)" #default="scope">
<slot :name="column.slotName" v-bind="scope" />
</template>
</el-table-column>
<template v-if="$slots.empty" #empty><slot name="empty" /></template>
</el-table>
<footer v-if="total !== undefined" class="data-table__pagination" aria-label="表格分页">
<div class="data-table__pagination-left">
<slot name="pagination-left" :total="normalizedTotal" :page="currentPage" :page-size="effectivePageSize" :page-count="pageCount">
<span v-if="pageCount > 0">共 {{ normalizedTotal }} 条 · 第 {{ currentPage }} / {{ pageCount }} 页</span>
<span v-else>共 0 条</span>
</slot>
</div>
<div class="data-table__pagination-controls">
<label class="data-table__page-size">
<span>每页</span>
<el-select :model-value="effectivePageSize" :disabled="loading" aria-label="每页条数" @update:model-value="updatePageSize">
<el-option v-for="size in normalizedPageSizes" :key="size" :label="String(size)" :value="size" />
</el-select>
<span>条</span>
</label>
<nav v-if="pageCount > 0" class="data-table__page-buttons" aria-label="页码">
<el-button class="data-table__page-button" :disabled="loading || currentPage <= 1" aria-label="上一页" title="上一页" @click="setPage(currentPage - 1)"><ChevronLeft :size="16" /></el-button>
<template v-for="item in paginationItems" :key="item">
<span v-if="typeof item !== 'number'" class="data-table__page-ellipsis" aria-hidden="true">...</span>
<el-button
v-else
class="data-table__page-button"
:type="item === currentPage ? 'primary' : undefined"
:disabled="loading"
:aria-current="item === currentPage ? 'page' : undefined"
:aria-label="`第 ${item} 页`"
:title="`第 ${item} 页`"
@click="setPage(item)"
>{{ item }}</el-button>
</template>
<el-button class="data-table__page-button" :disabled="loading || currentPage >= pageCount" aria-label="下一页" title="下一页" @click="setPage(currentPage + 1)"><ChevronRight :size="16" /></el-button>
</nav>
</div>
</footer>
</div>
</template>
<style scoped>
.data-table { min-width: 0; }
2026-08-06 20:14:56 +08:00
.data-table__toolbar { display: flex; min-height: 72px; align-items: center; justify-content: space-between; gap: 16px; padding: 12px 18px; border-bottom: 1px solid var(--cc-border); }
2026-08-10 16:24:54 +08:00
.data-table__toolbar.is-compact { min-height: 56px; justify-content: flex-end; padding: 8px 14px; }
2026-08-06 20:14:56 +08:00
.data-table__toolbar-start { min-width: 0; flex: 1; }
.data-table__toolbar-start :deep(h2) { margin: 0; color: var(--cc-text); font-size: 16px; line-height: 1.4; }
.data-table__toolbar-start :deep(p) { margin: 4px 0 0; color: var(--cc-muted); font-size: 12px; line-height: 1.5; }
.data-table__toolbar-actions { display: flex; flex: 0 0 auto; align-items: center; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
2026-08-10 17:42:17 +08:00
.data-table__business-actions, .data-table__utility-actions, .data-table__toolbar-end { display: flex; min-width: 0; align-items: center; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
.data-table__utility-actions { flex: 0 0 auto; }
2026-08-06 20:14:56 +08:00
.data-table__toolbar-actions :deep(.el-button + .el-button) { margin-left: 0; }
.data-table__pagination { display: flex; min-height: 58px; align-items: center; justify-content: space-between; gap: 16px; padding: 12px 18px; border-top: 1px solid var(--cc-border); color: var(--cc-muted); font-size: 12px; }
.data-table__pagination-left { display: flex; min-width: 0; flex: 1; align-items: center; gap: 8px; }
.data-table__pagination-controls, .data-table__page-size, .data-table__page-buttons { display: flex; align-items: center; gap: 8px; }
.data-table__pagination-controls { min-width: 0; flex-wrap: wrap; justify-content: flex-end; }
.data-table__page-size :deep(.el-select) { width: 82px; }
.data-table__page-buttons { gap: 4px; }
.data-table__page-button { width: 32px; min-width: 32px; height: 32px; padding: 0; margin-left: 0; }
.data-table__page-ellipsis { display: inline-flex; width: 24px; height: 32px; align-items: center; justify-content: center; }
2026-08-17 16:45:46 +08:00
@media (min-width: 1920px) {
.data-table__toolbar { min-height: 64px; gap: 12px; padding: 10px 14px; }
.data-table__toolbar.is-compact { min-height: 50px; padding: 6px 12px; }
.data-table__toolbar-actions,
.data-table__business-actions,
.data-table__utility-actions,
.data-table__toolbar-end { gap: 6px; }
.data-table__pagination { min-height: 52px; gap: 12px; padding: 10px 14px; }
.data-table__pagination-left,
.data-table__pagination-controls,
.data-table__page-size,
.data-table__page-buttons { gap: 6px; }
.data-table__page-button { width: 30px; min-width: 30px; height: 30px; }
.data-table__page-ellipsis { width: 22px; height: 30px; }
}
2026-08-10 17:42:17 +08:00
@media (max-width: 720px) { .data-table__toolbar, .data-table__toolbar.is-compact { min-height: 0; align-items: stretch; flex-direction: column; padding: 14px; } .data-table__toolbar-actions { width: 100%; align-items: flex-start; flex-wrap: wrap; justify-content: flex-start; } .data-table__toolbar-actions.has-business-actions { display: grid; grid-template-columns: minmax(0, 1fr) auto; } .data-table__business-actions { justify-content: flex-start; } .data-table__utility-actions { align-items: flex-start; justify-content: flex-end; } .data-table__toolbar-end { justify-content: flex-start; } .data-table__toolbar-actions :deep(.el-button) { max-width: 100%; min-height: 40px; } .data-table__pagination { align-items: flex-start; flex-direction: column; } .data-table__pagination-left, .data-table__pagination-controls, .data-table__page-buttons { width: 100%; } .data-table__pagination-controls { justify-content: flex-start; } .data-table__page-buttons { flex-wrap: wrap; } .data-table__page-button { width: 44px; min-width: 44px; height: 44px; } .data-table__page-ellipsis { height: 44px; } }
</style>