点击工具栏打开可筛选、复制的只读弹层,替换原行列点选复制模式,且不写回业务数据。 Co-authored-by: Cursor <cursoragent@cursor.com>
276 lines
7.4 KiB
Vue
276 lines
7.4 KiB
Vue
<!--
|
||
主列表薄封装:在 el-table 上启用列宽拖拽,并按 table-key 持久化到 localStorage。
|
||
用法:将 <el-table class="list-table" …> 换成 <ListTable table-key="crm-customer" class="list-table" …>
|
||
Excel 查看:工具栏打开只读 Univer 弹层,本组件提供 getExcelSnapshot()。
|
||
-->
|
||
<template>
|
||
<el-table
|
||
ref="tableRef"
|
||
v-bind="tableAttrs"
|
||
:data-list-excel-copy="excelCopy ? 'on' : undefined"
|
||
:border="resolvedBorder"
|
||
:allow-drag-last-column="true"
|
||
:class="tableClass"
|
||
@header-dragend="handleHeaderDragEnd"
|
||
>
|
||
<slot />
|
||
</el-table>
|
||
</template>
|
||
|
||
<script setup lang="ts">
|
||
import {
|
||
computed,
|
||
nextTick,
|
||
onActivated,
|
||
onBeforeUnmount,
|
||
onDeactivated,
|
||
onMounted,
|
||
ref,
|
||
unref,
|
||
useAttrs,
|
||
watch
|
||
} from 'vue'
|
||
import {
|
||
buildExcelSnapshot,
|
||
isCopyableColumn,
|
||
type ListExcelColumn,
|
||
type ListExcelSnapshot
|
||
} from '@/utils/list-excel-copy'
|
||
import {
|
||
isFixedNarrowListColumnKey,
|
||
resolveListColumnKey,
|
||
usePersistedListColumnWidths
|
||
} from '@/composables/usePersistedListColumnWidths'
|
||
|
||
defineOptions({ name: 'ListTable', inheritAttrs: false })
|
||
|
||
const props = withDefaults(
|
||
defineProps<{
|
||
/** 表格唯一标识,用于 localStorage 分区(同页多表必须不同) */
|
||
tableKey: string
|
||
/** 是否持久化列宽,默认 true */
|
||
persistColumnWidth?: boolean
|
||
/** 是否开启 border(列宽拖拽依赖);默认 true */
|
||
border?: boolean
|
||
/** 是否允许 Excel 只读查看,默认 true */
|
||
excelCopy?: boolean
|
||
}>(),
|
||
{
|
||
persistColumnWidth: true,
|
||
border: true,
|
||
excelCopy: true
|
||
}
|
||
)
|
||
|
||
const attrs = useAttrs()
|
||
const tableRef = ref<any>(null)
|
||
const { setWidth, applyToTable, resetWidths, getWidths } = usePersistedListColumnWidths(
|
||
computed(() => props.tableKey)
|
||
)
|
||
|
||
const resolvedBorder = computed(() => props.border !== false)
|
||
|
||
const tableClass = computed(() => {
|
||
const extra = attrs.class
|
||
return ['list-table', extra]
|
||
})
|
||
|
||
const tableAttrs = computed(() => {
|
||
const raw = { ...attrs } as Record<string, unknown>
|
||
delete raw.class
|
||
delete raw.border
|
||
// 避免与内部 handler 重复绑定(父级若仍监听,下面会手动转发)
|
||
delete raw.onHeaderDragend
|
||
delete raw.onHeaderDragEnd
|
||
return raw
|
||
})
|
||
|
||
const parentHeaderDragEnd = computed(() => {
|
||
const a = attrs as Record<string, unknown>
|
||
return (a.onHeaderDragend || a.onHeaderDragEnd) as
|
||
| ((...args: any[]) => void)
|
||
| Array<(...args: any[]) => void>
|
||
| undefined
|
||
})
|
||
|
||
let applyTimer: ReturnType<typeof setTimeout> | null = null
|
||
let mountApplyTimer: ReturnType<typeof setTimeout> | null = null
|
||
|
||
const scheduleApply = () => {
|
||
if (!props.persistColumnWidth) return
|
||
if (!Object.keys(getWidths()).length) return
|
||
if (applyTimer) clearTimeout(applyTimer)
|
||
applyTimer = setTimeout(() => {
|
||
nextTick(() => {
|
||
applyToTable(tableRef.value)
|
||
})
|
||
}, 16)
|
||
}
|
||
|
||
const clearApplyTimers = () => {
|
||
if (applyTimer) {
|
||
clearTimeout(applyTimer)
|
||
applyTimer = null
|
||
}
|
||
if (mountApplyTimer) {
|
||
clearTimeout(mountApplyTimer)
|
||
mountApplyTimer = null
|
||
}
|
||
}
|
||
|
||
const handleHeaderDragEnd = (
|
||
newWidth: number,
|
||
oldWidth: number,
|
||
column: any,
|
||
event: MouseEvent
|
||
) => {
|
||
if (props.persistColumnWidth) {
|
||
const key = resolveListColumnKey(column)
|
||
if (key && !isFixedNarrowListColumnKey(key)) setWidth(key, newWidth)
|
||
}
|
||
|
||
const parent = parentHeaderDragEnd.value
|
||
if (typeof parent === 'function') {
|
||
parent(newWidth, oldWidth, column, event)
|
||
} else if (Array.isArray(parent)) {
|
||
parent.forEach((fn) => fn?.(newWidth, oldWidth, column, event))
|
||
}
|
||
}
|
||
|
||
function readColumns(): ListExcelColumn[] {
|
||
const cols = tableRef.value?.store?.states?.columns
|
||
const list = (unref(cols) || []) as Array<Record<string, unknown>>
|
||
return list.map((col) => ({
|
||
id: String(col.id ?? ''),
|
||
label: String(col.label ?? ''),
|
||
type: col.type ? String(col.type) : undefined,
|
||
className: String(col.className ?? '')
|
||
}))
|
||
}
|
||
|
||
function tableRoot(): HTMLElement | null {
|
||
const el = tableRef.value?.$el as HTMLElement | undefined
|
||
return el ?? null
|
||
}
|
||
|
||
function bodyRows(): HTMLTableRowElement[] {
|
||
const root = tableRoot()
|
||
if (!root) return []
|
||
return Array.from(root.querySelectorAll('.el-table__body-wrapper tbody > tr.el-table__row'))
|
||
}
|
||
|
||
/** 当前可见列 + 当前页行文本,供 Excel 只读弹层使用 */
|
||
function getExcelSnapshot(): ListExcelSnapshot {
|
||
if (!props.excelCopy) return { headers: [], rows: [] }
|
||
const columns = readColumns()
|
||
const copyable = columns.filter((col) => col.id && isCopyableColumn(col))
|
||
const rows = bodyRows()
|
||
const rowValues = rows.map((row) =>
|
||
copyable.map((col) => {
|
||
const td = row.querySelector(`td.${CSS.escape(col.id)}`)
|
||
return td?.textContent ?? ''
|
||
})
|
||
)
|
||
// rowValues 已按可复制列对齐,传入过滤后的 columns
|
||
return buildExcelSnapshot({ columns: copyable, rowValues })
|
||
}
|
||
|
||
function bindSnapshotApi() {
|
||
const root = tableRoot()
|
||
if (!root) return
|
||
;(root as HTMLElement & { __sxGetExcelSnapshot?: () => ListExcelSnapshot }).__sxGetExcelSnapshot =
|
||
getExcelSnapshot
|
||
}
|
||
|
||
function unbindSnapshotApi() {
|
||
const root = tableRoot()
|
||
if (!root) return
|
||
delete (root as HTMLElement & { __sxGetExcelSnapshot?: () => ListExcelSnapshot })
|
||
.__sxGetExcelSnapshot
|
||
}
|
||
|
||
onMounted(() => {
|
||
scheduleApply()
|
||
mountApplyTimer = setTimeout(() => scheduleApply(), 100)
|
||
bindSnapshotApi()
|
||
})
|
||
|
||
onBeforeUnmount(() => {
|
||
unbindSnapshotApi()
|
||
clearApplyTimers()
|
||
})
|
||
|
||
onDeactivated(() => {
|
||
clearApplyTimers()
|
||
})
|
||
|
||
onActivated(() => {
|
||
scheduleApply()
|
||
bindSnapshotApi()
|
||
})
|
||
|
||
watch(
|
||
() => (attrs as any).data,
|
||
() => {
|
||
scheduleApply()
|
||
},
|
||
{ deep: false }
|
||
)
|
||
|
||
watch(
|
||
() => props.tableKey,
|
||
() => scheduleApply()
|
||
)
|
||
|
||
watch(
|
||
() => {
|
||
const cols = tableRef.value?.store?.states?.columns
|
||
return unref(cols)?.length ?? 0
|
||
},
|
||
() => {
|
||
scheduleApply()
|
||
}
|
||
)
|
||
|
||
/**
|
||
* 代理底层 el-table,保证父组件 ref 上的 clearSelection / setCurrentRow / doLayout 等仍可用。
|
||
* 必须实现 has:Vue exposeProxy 用 `key in target` 决定是否转发,空对象 Proxy 若不声明 has
|
||
* 则 `in` 恒为 false,父组件拿到的方法永远是 undefined。
|
||
*/
|
||
const exposed = new Proxy(
|
||
{},
|
||
{
|
||
get(_target, prop) {
|
||
if (prop === 'elTableRef') return tableRef
|
||
if (prop === 'applyColumnWidths') {
|
||
return () => applyToTable(tableRef.value)
|
||
}
|
||
if (prop === 'resetColumnWidths') {
|
||
return () => {
|
||
resetWidths()
|
||
}
|
||
}
|
||
if (prop === 'getExcelSnapshot') return getExcelSnapshot
|
||
const table = tableRef.value
|
||
if (!table) return undefined
|
||
const value = table[prop as keyof typeof table]
|
||
return typeof value === 'function' ? value.bind(table) : value
|
||
},
|
||
has(_target, prop) {
|
||
if (
|
||
prop === 'elTableRef' ||
|
||
prop === 'applyColumnWidths' ||
|
||
prop === 'resetColumnWidths' ||
|
||
prop === 'getExcelSnapshot'
|
||
) {
|
||
return true
|
||
}
|
||
const table = tableRef.value
|
||
return !!table && prop in table
|
||
}
|
||
}
|
||
)
|
||
|
||
defineExpose(exposed)
|
||
</script>
|