yin a796f968e3 feat(order): 新增批量导入运单号,统一列表与打印的运单号取值
- 新增 order.pendingOrder.importWaybill 接口与 ImportWaybillForm:
  粘贴「发货单号 + 货主备注 + 运单号」批量写入,逐行校验与去重,
  返回逐条结果明细,单条失败不影响其它记录
- 待处理订单工具栏新增「导入运单号」(无需勾选);手工录入运单号补充可选的
  快递编码与物流接口名称,空值不下发
- 订单各列表统一「运单号」列与 waybill_codes 筛选字段,取值统一走
  toWaybillCodes / waybillCodesFormatter,兼容 waybill_codes / express_numbers 等来源
- 波次打印与确认打印新增 resolveWaveOrderWaybillText:
  按 expresses[].waybill_code → waybill_codes/express_numbers → waybill_code/
  waybill_no/tracking_no 回退,明确不读取 express_code(快递公司编码),
  模板同时写入 express_code 与 waybill_code;面板列名统一为「运单号」
- 新增运单号命名改动清单、同数据不同字段名对照表等文档,并更新单号字段命名快照
2026-11-23 18:00:10 +08:00

2795 lines
87 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<div class="upper-table-container" :class="[tableSize, { 'is-fixed-row-height': virtualOscillating }]">
<!-- 表格区域 -->
<div class="table-container" ref="tableContainer">
<el-table
v-loading="loading"
ref="tableRef"
:data="tableRenderData"
:highlight-current-row="highlightCurrentRow"
:row-key="rowKey"
:current-row-key="currentRowKey"
@current-change="handleCurrentChange"
@row-click="handleRowClick"
@row-contextmenu="handleRowContextMenu"
@sort-change="handleSortChange"
@selection-change="handleSelectionChangeEvent"
style="width: 100%"
:size="tableSize"
:border="border"
:stripe="stripe"
:show-header="showHeader"
:empty-text="emptyText"
:fit="fit"
:tooltip-effect="tooltipEffect"
:row-class-name="getRowClassName"
:row-style="getRowStyle"
:span-method="spanMethod"
height="100%"
>
<!-- 原生选择列:selectionMode='native'(树形表格推荐,展开箭头落在首个数据列) -->
<el-table-column
v-if="showSelection && selectionMode === 'native'"
type="selection"
:width="selectionColumnWidth"
fixed="left"
:selectable="selectable"
/>
<!-- 自定义选择列 -->
<el-table-column v-else-if="showSelection" :width="selectionColumnWidth" fixed="left">
<!-- 表头 -->
<template #header>
<div class="custom-selection-header" @click.stop="toggleAllSelection">
<el-checkbox
v-model="isAllSelectedInView"
:indeterminate="isIndeterminate"
@click.stop="toggleAllSelection"
/>
</div>
</template>
<!-- 单元格 -->
<template #default="scope">
<template v-if="isVirtualSpacerRow(scope.row)">
<span class="virtual-spacer-cell"></span>
</template>
<template v-else>
<div class="custom-selection-cell" @click.stop="toggleRowSelection(scope.row)">
<el-checkbox
:model-value="isRowSelected(scope.row)"
:key="`checkbox-${getRowKey(scope.row)}-${checkboxUpdateKey}`"
@click.stop="toggleRowSelection(scope.row)"
/>
</div>
</template>
</template>
</el-table-column>
<!-- 展开行(showExpand 开启时渲染,内容由 expand 插槽提供) -->
<el-table-column v-if="showExpand" type="expand" width="48" fixed="left">
<template #default="scope">
<slot name="expand" :row="scope.row" />
</template>
</el-table-column>
<!-- 动态列 -->
<template v-for="column in displayColumns" :key="column.prop">
<el-table-column
v-if="column.prop"
:prop="column.prop"
:label="column.label"
:width="column.width"
:min-width="column.minWidth"
:fixed="column.fixed"
:sortable="column.sortable"
:sort-by="column.sortBy"
:sort-orders="column.sortOrders"
:resizable="column.resizable"
:show-overflow-tooltip="column.showOverflowTooltip === true"
:align="column.align || defaultAlign"
:header-align="column.headerAlign || column.align || defaultAlign"
:class-name="column.className"
:label-class-name="column.labelClassName"
:filters="column.filters"
:filter-method="column.filterMethod"
:filtered-value="column.filteredValue"
:filter-multiple="column.filterMultiple"
:filter-placement="column.filterPlacement"
>
<template #default="scope">
<template v-if="isVirtualSpacerRow(scope.row)">
<span class="virtual-spacer-cell"></span>
</template>
<template v-else>
<slot :name="`column-${column.prop}`" :row="scope.row" :index="scope.$index">
<template v-if="isWaybillCodeColumn(column) && !column.template">
<WaybillCodeActions
v-if="getWaybillCellCodes(scope.row, column).length"
:codes="getWaybillCellCodes(scope.row, column)"
:label="column.label || '运单号'"
:collapse="column.copyMultiCollapse === true"
:align="column.align || defaultAlign"
/>
<span
v-else-if="column.formatter"
v-html="getFormattedCell(scope.row, column, scope.row[column.prop], scope.$index)"
></span>
<span v-else style="color:#909399">—</span>
</template>
<template v-else-if="column.copyAction">
<div v-if="getCopyActionCodes(scope.row, column).length" class="click-copy-list">
<template
v-for="(code, codeIndex) in getVisibleCopyActionCodes(scope.row, column)"
:key="`${getMultiCopyCellKey(scope.row, column)}-${codeIndex}-${code}`"
>
<span
class="click-copy-link"
role="button"
tabindex="0"
:title="getCopyActionTitle(column)"
@click.stop="handleCopyActionClick(code, column)"
@keydown.enter.prevent="handleCopyActionClick(code, column)"
>
{{ code }}
</span>
</template>
<button
v-if="shouldShowCopyCollapseToggle(scope.row, column)"
type="button"
class="click-copy-toggle"
:title="isCopyCellExpanded(scope.row, column) ? '收起' : '展开查看全部'"
@click.stop="toggleCopyCellExpand(scope.row, column)"
>
{{ isCopyCellExpanded(scope.row, column) ? '收起' : `+${getHiddenCopyActionCount(scope.row, column)}` }}
</button>
</div>
<span v-else style="color:#909399">—</span>
</template>
<template v-else-if="shouldCollapseTextCell(scope.row, column, scope.$index)">
<div class="text-collapse-cell">
<span
class="text-collapse-text"
:title="isTextCellExpanded(scope.row, column) ? '' : getTextCollapseFullText(scope.row, column, scope.$index)"
>{{ getVisibleTextCollapseText(scope.row, column, scope.$index) }}</span>
<button
type="button"
class="text-collapse-toggle"
:title="isTextCellExpanded(scope.row, column) ? '收起' : '展开全部'"
@click.stop="toggleTextCellExpand(scope.row, column)"
>
{{ isTextCellExpanded(scope.row, column) ? '收起' : '展开' }}
</button>
</div>
</template>
<template v-else-if="column.formatter">
<span v-html="getFormattedCell(scope.row, column, scope.row[column.prop], scope.$index)"></span>
</template>
<template v-else-if="column.prop === 'order_flag'">
<el-tooltip
:content="getOrderFlagFullText(scope.row[column.prop])"
placement="top"
:disabled="!getOrderFlagFullText(scope.row[column.prop])"
:show-after="400"
>
<span
:class="getDefaultCellTextClass(column.prop, scope.row[column.prop])"
role="button"
tabindex="0"
@click.stop="copyOrderFlagText(scope.row[column.prop])"
@keydown.enter.prevent="copyOrderFlagText(scope.row[column.prop])"
>
{{ getOrderFlagCellText(scope.row[column.prop]) }}
</span>
</el-tooltip>
</template>
<template v-else-if="column.prop === 'buyer_message'">
<template v-if="scope.row[column.prop]">
<el-tooltip
:content="scope.row[column.prop]"
placement="top"
:show-after="400"
>
<span
class="buyer-message-text buyer-message-copyable"
role="button"
tabindex="0"
@click.stop="copyBuyerMessage(scope.row[column.prop])"
@keydown.enter.prevent="copyBuyerMessage(scope.row[column.prop])"
>
{{ truncateBuyerMessage(scope.row[column.prop]) }}
</span>
</el-tooltip>
</template>
<span v-else style="color:#909399">—</span>
</template>
<template v-else-if="column.template">
<component
:is="column.template"
:row="scope.row"
:column="scope.column"
:index="scope.$index"
/>
</template>
<template v-else-if="column.imgs">
<el-image
style="height: 23px; overflow: unset; margin: 0 3px"
v-for="(img, idx) in column.imgs(scope.row, scope.column, scope.$index)"
:key="idx"
:src="img"
:preview-src-list="column.imgs(scope.row, scope.column, scope.$index)"
preview-teleported
></el-image>
</template>
<span v-else :class="getDefaultCellTextClass(column.prop, scope.row[column.prop])">{{ scope.row[column.prop] }}</span>
</slot>
</template>
</template>
</el-table-column>
</template>
<!-- 空状态插槽 -->
<template #empty>
<slot name="empty">
<div class="empty-table">
<el-icon size="48" color="#c0c4cc"><Box /></el-icon>
<p>{{ emptyText }}</p>
</div>
</slot>
</template>
</el-table>
</div>
<!-- 分页区域 -->
<div class="pagination-container" v-if="showPagination">
<div class="pagination-info">
<!-- 左侧文案:默认「已选 N 条 + 查询用时」,页面可用 #pagination-info 精简(如只要「已选 N 项」) -->
<slot name="pagination-info" :count="selectedCount" :query-time="queryTime">
已选 {{ selectedCount }} 条,查询用时 {{ (queryTime / 1000).toFixed(2) }} 秒
</slot>
<!-- 可选扩展插槽:紧随“查询用时”展示统计/通知(如平均拣货/复核时长),页面按需提供内容 -->
<slot name="pagination-info-extra" />
</div>
<el-pagination
:current-page="pagination.currentPage"
:page-sizes="pageSizes"
:page-size="pagination.pageSize"
:total="total"
:layout="paginationLayout"
:background="paginationBackground"
:size="tableSize"
@size-change="handlePageSizeChange"
@current-change="handlePageChange"
/>
</div>
<SettingsDialog
v-model:visible="settingsVisible"
:initial-section="settingsInitialSection"
@columns-changed="rebuildColumnConfig"
>
<template #field-section>
<div class="field-section">
<div class="field-section-head">
<div>
<div class="field-section-title">列表字段</div>
<div class="field-section-desc">
当前表格:勾选显示列、拖动调整顺序;导出/导入配置与故障修复请前往「数据与维护」。
</div>
</div>
<el-button size="small" @click="resetColumnConfig">恢复默认</el-button>
</div>
<div class="column-config-list" ref="columnConfigListRef">
<template v-for="section in columnConfigDialogSections" :key="section.key">
<div class="column-config-section" :class="`column-config-section--${section.key}`">
<div class="column-config-section-title">{{ section.title }}</div>
<div class="column-config-section-body">
<div
v-for="(item, sIdx) in section.items"
:key="item.prop"
class="column-config-item"
:class="{
'is-fixed-column': section.key !== 'scroll',
'is-draggable': true,
'is-drag-over': dragOverProp === item.prop
}"
:draggable="true"
@dragstart="onColumnDragStart($event, item)"
@dragover.prevent="onColumnDragOver($event, item)"
@drop.prevent="onColumnDrop(item)"
@dragend="onColumnDragEnd"
>
<div class="column-config-main">
<span class="drag-handle" aria-hidden="true">⋮⋮</span>
<el-checkbox
:model-value="item.visible"
@change="(val: any) => onToggleColumnVisible(item.prop, !!val)"
>
{{ item.label || item.prop }}
</el-checkbox>
</div>
<div class="column-config-actions">
<!-- 不固定列:左箭头固定到左侧,右箭头固定到右侧 -->
<el-button
v-if="section.key === 'scroll'"
text
size="small"
class="cfg-fix-btn"
@click="setFixed(item.prop, 'left')"
title="固定到左侧"
>
←
</el-button>
<el-button
v-if="section.key === 'scroll'"
text
size="small"
class="cfg-fix-btn"
@click="setFixed(item.prop, 'right')"
title="固定到右侧"
>
→
</el-button>
<!-- 左固定列:→ 回到不固定列 -->
<el-button
v-if="section.key === 'fixed-left'"
text
size="small"
class="cfg-fix-btn"
@click="setFixed(item.prop, false)"
title="回到不固定列"
>
→
</el-button>
<!-- 右固定列:← 回到不固定列 -->
<el-button
v-if="section.key === 'fixed-right'"
text
size="small"
class="cfg-fix-btn"
@click="setFixed(item.prop, false)"
title="回到不固定列"
>
←
</el-button>
<el-button
text
size="small"
class="cfg-move-btn"
:disabled="sIdx === 0"
@click="moveColumn(item.prop, 'up')"
>
↑
</el-button>
<el-button
text
size="small"
class="cfg-move-btn"
:disabled="sIdx === section.items.length - 1"
@click="moveColumn(item.prop, 'down')"
>
↓
</el-button>
</div>
</div>
<div v-if="!section.items.length" class="column-config-empty">
<span>将列拖到此处固定</span>
</div>
</div>
</div>
</template>
</div>
</div>
</template>
</SettingsDialog>
<qrcode-dialog v-model:visible="waybillQrVisible" :code="waybillQrCode" />
</div>
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick, useAttrs } from 'vue'
import { Box } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/modules/user'
import { useExperimentalStore } from '@/stores/modules/experimental'
import { useTableColumnConfigStore } from '@/stores/modules/tableColumnConfig'
import type { ColumnConfigItem, TableColumnProfile } from '@/utils/table-column-config'
import QrcodeDialog from '@/components/QR/qrcode.vue'
import WaybillCodeActions from '@/components/waybill/WaybillCodeActions.vue'
import { isWaybillCodeColumn } from '@/components/waybill/waybill-column'
import SettingsDialog from '@/components/settings/SettingsDialog.vue'
defineOptions({
name: 'UpperTable'
})
const props = defineProps({
loading: {
type: Boolean,
default: false,
},
// 表格数据
data: {
type: Array as any,
default: () => [],
},
// 表格列配置
columns: {
type: Array as any,
default: () => [],
},
// 表格尺寸
tableSize: {
type: String,
default: 'small',
validator: (value: string) => ['large', 'default', 'small'].includes(value),
},
// 高亮当前行
highlightCurrentRow: {
type: Boolean,
default: true,
},
// 行唯一键
rowKey: {
type: [String, Function],
default: 'id',
},
// 当前选中行的key
currentRowKey: {
type: [String, Number],
default: '',
},
// 显示边框
border: {
type: Boolean,
default: true,
},
// 显示斑马纹
stripe: {
type: Boolean,
default: true,
},
// 显示表头
showHeader: {
type: Boolean,
default: true,
},
// 空数据文本
emptyText: {
type: String,
default: '暂无数据',
},
queryTime: {
type: Number,
default: 0,
},
// 列的宽度是否自撑开
fit: {
type: Boolean,
default: true,
},
// tooltip effect
tooltipEffect: {
type: String,
default: 'dark',
},
// 显示选择列
showSelection: {
type: Boolean,
default: false,
},
/**
* 选择列模式:
* - custom(默认):自带居中勾选列,支持虚拟滚动 / 外部选中同步
* - native:el-table 原生 type="selection",树形表格用它可避免展开箭头占用勾选列(行高与位置正常)
*/
selectionMode: {
type: String,
default: 'custom',
validator: (value: string) => ['custom', 'native'].includes(value),
},
// 是否显示展开行(展开内容由 expand 插槽提供)
showExpand: {
type: Boolean,
default: false,
},
// 是否可勾选函数
selectable: {
type: Function,
default: () => true,
},
// 外部传入的默认选中数据
defaultSelected: {
type: Array as any,
default: () => [],
},
// 是否自动同步外部选中状态到表格
autoSyncSelection: {
type: Boolean,
default: true,
},
// 选择列宽度
selectionColumnWidth: {
type: [String, Number],
default: 55,
},
// 选择列是否固定
selectionColumnFixed: {
type: [String, Boolean],
default: true,
},
// 分页配置
pagination: {
type: Object,
default: () => ({
currentPage: 1,
pageSize: 20,
total: 0,
}),
},
// 是否显示分页
showPagination: {
type: Boolean,
default: true,
},
// 分页每页显示个数选择器的选项设置
pageSizes: {
type: Array as any,
default: () => [10, 20, 50, 100, 200, 500],
},
// 分页布局
paginationLayout: {
type: String,
default: 'total, sizes, prev, pager, next, jumper',
},
// 分页背景色
paginationBackground: {
type: Boolean,
default: true,
},
enableColumnConfig: {
type: Boolean,
default: false,
},
tableId: {
type: String,
default: '',
},
columnConfigSchemaVersion: {
type: Number,
default: 1,
},
rowClassName: {
type: [String, Function],
default: '',
},
virtualThreshold: {
type: Number,
default: 80,
},
virtualMaxVisibleRows: {
type: Number,
default: 0,
},
virtualBufferRows: {
type: Number,
default: 16,
},
/**
* 表格工作模式(方案⑨ 双模式):
* - resource(开销优先,默认):减少资源开销,保证基础体验(⑦A:滚动停止后统一更新)
* - performance(性能优先):提升资源开销换取使用性能(⑦B:滚动中实时跟随)
*/
tableMode: {
type: String,
default: 'resource',
validator: (value: string) => ['performance', 'resource'].includes(value),
},
defaultAlign: {
type: String,
default: 'left',
validator: (value: string) => ['left', 'center', 'right'].includes(value),
},
// 合并单元格(透传给 el-table,部分页面按明细合并多行)
spanMethod: {
type: Function,
default: undefined,
},
})
const emit = defineEmits([
'current-change',
'selection-change',
'row-click',
'row-contextmenu',
'sort-change',
'page-size-change',
'page-change',
'refresh',
'select-all-change',
'row-selection-change',
])
// Refs
const tableRef = ref<any>(null)
const userStore = useUserStore()
const experimentalStore = useExperimentalStore()
const attrs = useAttrs()
/** 表格展示名称(页面通过 :title 传入,未声明为 prop,从 attrs 读取) */
const tableTitle = computed(() => String((attrs.title as string) || ''))
/** 设置中心可见性(字段设置 / 更多设置 / 标签排序 / 数据维护 统一入口) */
const settingsVisible = ref(false)
/** 打开时定位的分区:'field' = 当前表格的列表字段 */
const settingsInitialSection = ref('field')
type ColumnItem = {
prop?: string
label?: string
width?: number | string
fixed?: 'left' | 'right' | boolean
[key: string]: any
}
// State
// const visibleData = ref<any[]>([]) // Removed
// const rowHeight = ref(41) // Removed
// const bufferSize = ref(8) // Removed
// const offset = ref(0) // Removed
// const containerHeight = ref(0) // Removed
const selectedRows = ref<any[]>([])
const selectedRowKeys = ref<Set<any>>(new Set())
// const rowKeyMap = ref<Map<any, any>>(new Map()) // Removed
// const lastScrollTop = ref(0) // Removed
// let scrollTimer: any = null // Removed
const checkboxUpdateKey = ref<number | null>(null)
const editableColumnConfigs = ref<ColumnConfigItem[]>([])
const columnConfigMap = ref<Record<string, ColumnConfigItem>>({})
const draggingProp = ref<string>('')
const dragOverProp = ref<string>('')
const tableContainer = ref<HTMLElement | null>(null)
const bodyScrollEl = ref<HTMLElement | null>(null)
let scrollRaf: number | null = null
const columnConfigListRef = ref<HTMLElement | null>(null)
const virtualScrollTop = ref(0)
const virtualViewportHeight = ref(0)
/** 实测数据行行高(可视区数据行高度中位数),0 = 尚未测到;用于修正 spacer 占位高度 */
const measuredRowHeight = ref(0)
/** 已生效到虚拟窗口的滚动方向(滚动中变化不立即改缓冲区,避免窗口行数闪变触发整表重建) */
const windowScrollDirection = ref<'up' | 'down'>('down')
/** tableRenderData 数组复用缓存(窗口内容未变时返回同一引用,跳过 el-table 全量重算) */
let renderRowsCache: {
source: unknown
start: number
end: number
top: number
bottom: number
firstRow: unknown
lastRow: unknown
rows: any[]
} | null = null
/** 行 key 缓存(多列单元格重复取 key,避免每次调用 rowKey 函数) */
const rowKeyCache = new WeakMap<object, unknown>()
/** 多值单号解析缓存(copyAction 列每单元格会被多次求值) */
const copyCodesCache = new WeakMap<object, Map<string, string[]>>()
/** 运单号列解析缓存(统一操作菜单每单元格会被多次求值) */
const waybillCodesCache = new WeakMap<object, Map<string, string[]>>()
/** 超长文本收起结果的完整文本缓存(避免重复 formatter + 去标签正则) */
const textCollapseCache = new WeakMap<object, Map<string, string>>()
/** 虚拟滚动高度抖动兜底(见 enableFixedRowHeightFallback) */
const virtualOscillating = ref(false)
/** 滚动窗口更新后校正 scrollTop 的 rAF 句柄 */
let reconcileRaf: number | null = null
/** 连续被浏览器改写 scrollTop 的次数(用于识别死循环) */
let reconcilePasses = 0
let reconcileResetTimer: ReturnType<typeof setTimeout> | null = null
/** 观察滚动区域尺寸变化,窗口缩放/详情区拖拽时同步视口高度 */
let tableResizeObserver: ResizeObserver | null = null
/** 当前滚动方向(方案⑥:方向感知 buffer,减少向上滚动"真空期") */
const scrollDirection = ref<'up' | 'down'>('down')
/** 方案⑦:滚动停止后统一更新窗口的防抖定时器 */
let scrollSettleTimer: ReturnType<typeof setTimeout> | null = null
/** 方案⑦+性能优化:performance 模式窗口同步节流,记录上次同步时间(避免每帧触发 el-table 全量重算) */
let lastWindowSyncTime = 0
/** 当前生效的表格工作模式(优先读 localStorage,兜底 props.tableMode) */
const activeTableMode = ref<'performance' | 'resource'>(props.tableMode as 'performance' | 'resource')
const dragAutoScrollStep = ref(0)
let dragAutoScrollRaf: number | null = null
const waybillQrVisible = ref(false)
const waybillQrCode = ref('')
const expandedMultiCopyCells = ref<Set<string>>(new Set())
/** 超长文本收起:已展开的单元格(key = rowKey::prop) */
const expandedTextCells = ref<Set<string>>(new Set())
type VirtualSpacerRow = {
__virtualSpacer: true
__virtualSpacerType: 'top' | 'bottom'
__virtualSpacerHeight: number
}
const normalizedColumns = computed<ColumnItem[]>(() => {
return (props.columns || []).filter((column: ColumnItem) => !!column?.prop)
})
/** 列配置项与列定义合并后的 fixed 语义(用于字段设置与表头顺序) */
function effectiveColumnFixed(item: ColumnConfigItem, col: ColumnItem): 'left' | 'right' | undefined {
if (item.fixed === false) return undefined
const f = item.fixed ?? col.fixed
if (f === true || f === 'left') return 'left'
if (f === 'right') return 'right'
return undefined
}
function isColumnOrderLocked(_item: ColumnConfigItem): boolean {
// 全部列均支持排序(固定列可在其所在区域内拖动排序)
return false
}
function normalizeFromParts(left: ColumnConfigItem[], mid: ColumnConfigItem[], right: ColumnConfigItem[]) {
let o = 0
return [...left, ...mid, ...right].map((c) => ({ ...c, order: o++ }))
}
/** 按列定义顺序拆成左固定 / 可排序 / 右固定;各自按当前 order 排序 */
function partitionColumnConfigsTriplet(configs: ColumnConfigItem[]) {
const map = new Map(configs.map((c) => [c.prop, c]))
const left: ColumnConfigItem[] = []
const mid: ColumnConfigItem[] = []
const right: ColumnConfigItem[] = []
for (const col of normalizedColumns.value) {
const p = String(col.prop || '')
const item = map.get(p)
if (!item) continue
const z = effectiveColumnFixed(item, col)
if (z === 'left') left.push(item)
else if (z === 'right') right.push(item)
else mid.push(item)
}
left.sort((a, b) => a.order - b.order)
mid.sort((a, b) => a.order - b.order)
right.sort((a, b) => a.order - b.order)
return { left, mid, right }
}
function normalizeColumnConfigOrders(configs: ColumnConfigItem[]): ColumnConfigItem[] {
const { left, mid, right } = partitionColumnConfigsTriplet(configs)
return normalizeFromParts(left, mid, right)
}
const effectiveTableId = computed(() => props.tableId?.trim())
const columnConfigStorageKey = computed(() => {
if (!props.enableColumnConfig || !effectiveTableId.value) return ''
const userId = userStore.user?.username || userStore.user?.id || 'unknown'
const roleId = userStore.roleId || 'default'
return `upper_table_columns_${userId}_${roleId}_${effectiveTableId.value}`
})
const displayColumns = computed(() => {
if (!props.enableColumnConfig || !effectiveTableId.value) {
return normalizedColumns.value
}
const configMap = columnConfigMap.value
return normalizedColumns.value
.filter((column) => {
const prop = String(column.prop || '')
const cfg = configMap[prop]
return cfg ? cfg.visible !== false : true
})
.sort((a, b) => {
const aOrder = configMap[String(a.prop || '')]?.order ?? Number.MAX_SAFE_INTEGER
const bOrder = configMap[String(b.prop || '')]?.order ?? Number.MAX_SAFE_INTEGER
return aOrder - bOrder
})
.map((column) => {
const cfg = configMap[String(column.prop || '')]
if (!cfg) return column
// 操作列宽度由页面定义决定:历史保存的列宽可能偏窄,会把行内按钮裁掉
const isActionColumn = String(column.prop || '') === 'actions'
return {
...column,
width: isActionColumn ? column.width : (cfg.width ?? column.width),
fixed: cfg.fixed === false ? undefined : (cfg.fixed ?? column.fixed)
}
})
})
/** 字段设置弹窗分组:固定列仅显示/隐藏,中间块可拖动排序 */
const columnConfigDialogSections = computed(() => {
const { left, mid, right } = partitionColumnConfigsTriplet(editableColumnConfigs.value)
const sections: { key: string; title: string; items: ColumnConfigItem[] }[] = []
if (left.length || true) {
sections.push({
key: 'fixed-left',
title: '左侧固定',
items: left
})
}
if (mid.length) {
sections.push({
key: 'scroll',
title: '不固定列',
items: mid
})
}
if (right.length || true) {
sections.push({
key: 'fixed-right',
title: '右侧固定',
items: right
})
}
return sections
})
// Computed
/**
* 各尺寸下 el-table 的理论单行高度(含 1px 分隔线),仅作兜底。
* 真实行高会在渲染后实测(measuredRowHeight):行高与 spacer 占位不一致会让
* 表格内容总高度随虚拟窗口变化,表现为滚动时行位置跳动、滚动条来回弹。
*/
const assumedRowHeight = computed(() => {
if (props.tableSize === 'large') return 49
if (props.tableSize === 'default') return 41
return 32
})
/** 虚拟滚动计算用行高:优先实测值,兜底理论值 */
const virtualRowHeight = computed(() => {
return measuredRowHeight.value > 0 ? measuredRowHeight.value : assumedRowHeight.value
})
const shouldUseVirtual = computed(() => {
return props.data.length >= props.virtualThreshold
})
/** 模式驱动的 buffer 基数:performance=10(配合方向侧加倍 → 单侧 20 行滚动余量),resource=8 */
const effectiveBufferRows = computed(() => {
return activeTableMode.value === 'performance'
? Math.max(8, Math.floor(props.virtualBufferRows * 0.625))
: Math.max(4, Math.floor(props.virtualBufferRows / 2))
})
/**
* 方向感知缓冲行数(方案⑥):滚动方向一侧加倍。
* 缓冲只在下一次窗口更新时生效(windowScrollDirection),避免滚动中 buffer 闪变触发整表重建。
*/
const virtualTopBufferRows = computed(() => {
return windowScrollDirection.value === 'up'
? effectiveBufferRows.value * 2
: effectiveBufferRows.value
})
const virtualBottomBufferRows = computed(() => {
return windowScrollDirection.value === 'down'
? effectiveBufferRows.value * 2
: effectiveBufferRows.value
})
const virtualVisibleCount = computed(() => {
const viewportCount = virtualViewportHeight.value
? Math.ceil(virtualViewportHeight.value / virtualRowHeight.value) + virtualTopBufferRows.value + virtualBottomBufferRows.value
: 30
if (props.virtualMaxVisibleRows > 0) {
return Math.min(props.virtualMaxVisibleRows, viewportCount)
}
// 量化到 4 行:滚动条出现/消失造成的 1-2 行波动不再触发整表重建
return Math.ceil(viewportCount / 4) * 4
})
const virtualStartIndex = computed(() => {
if (!shouldUseVirtual.value) return 0
return Math.max(0, Math.floor(virtualScrollTop.value / virtualRowHeight.value) - virtualTopBufferRows.value)
})
const virtualEndIndex = computed(() => {
if (!shouldUseVirtual.value) return props.data.length
return Math.min(props.data.length, virtualStartIndex.value + virtualVisibleCount.value)
})
const virtualTopPadding = computed(() => {
if (!shouldUseVirtual.value) return 0
// 取整避免亚像素累积:spacer 与真实行高的小数差会被浏览器逐行取整放大
return Math.round(virtualStartIndex.value * virtualRowHeight.value)
})
const virtualBottomPadding = computed(() => {
if (!shouldUseVirtual.value) return 0
return Math.max(0, Math.round((props.data.length - virtualEndIndex.value) * virtualRowHeight.value))
})
const virtualVisibleRows = computed(() => {
if (!shouldUseVirtual.value) return props.data
return props.data.slice(virtualStartIndex.value, virtualEndIndex.value)
})
const tableRenderData = computed(() => {
if (!shouldUseVirtual.value) return props.data
const start = virtualStartIndex.value
const end = virtualEndIndex.value
const top = virtualTopPadding.value
const bottom = virtualBottomPadding.value
// 窗口内容没变时复用同一数组引用:Vue 的 computed 不会把"引用没变"通知给 el-table,
// 从而避免一次耗时数百毫秒的 :data 全量重算(滚动方向/视口几像素变化经常命中)
const cache = renderRowsCache
if (cache && cache.source === props.data && cache.start === start && cache.end === end
&& cache.top === top && cache.bottom === bottom
&& cache.firstRow === props.data[start] && cache.lastRow === props.data[end - 1]) {
return cache.rows
}
const rows: any[] = []
if (top > 0) {
rows.push(createVirtualSpacerRow('top', top))
}
rows.push(...virtualVisibleRows.value)
if (bottom > 0) {
rows.push(createVirtualSpacerRow('bottom', bottom))
}
renderRowsCache = {
source: props.data,
start,
end,
top,
bottom,
firstRow: props.data[start],
lastRow: props.data[end - 1],
rows
}
return rows
})
const total = computed(() => {
return props.pagination.total || props.data.length
})
const selectableRows = computed(() => {
return props.data.filter((row: any, index: number) => props.selectable(row, index))
})
const isAllSelected = computed(() => {
if (selectableRows.value.length === 0) return false
return selectableRows.value.every((row: any) =>
selectedRowKeys.value.has(getRowKey(row))
)
})
const isAllSelectedInView = computed({
get() {
return props.data.length > 0 && props.data.length === selectedRows.value.length
},
set(val) {
toggleAllSelection()
}
})
const isIndeterminate = computed(() => {
return props.data.length > selectedRows.value.length && selectedRows.value.length > 0
})
const selectedCount = computed(() => {
return selectedRows.value.length
})
// Watchers
watch(() => props.data, () => {
clearSelection()
expandedMultiCopyCells.value = new Set()
expandedTextCells.value = new Set()
syncVirtualViewport()
})
watch(
[() => props.columns, () => props.enableColumnConfig, () => props.tableId, () => userStore.roleId, () => userStore.user],
() => {
rebuildColumnConfig()
},
{ immediate: true, deep: true }
)
watch(() => props.defaultSelected, (newVal) => {
if (props.autoSyncSelection) {
setSelectionFromExternal(newVal)
}
}, { deep: true })
watch(selectedRows, (newVal) => {
emit('selection-change', [...newVal])
}, { deep: true })
/** 原生选择列(selectionMode='native')的勾选同步:回写 selectedRows,复用统一的 selection-change 事件 */
function handleSelectionChangeEvent(rows: any[]) {
if (props.selectionMode !== 'native') return
selectedRows.value = [...rows]
selectedRowKeys.value = new Set(rows.map((row: any) => getRowKey(row)))
}
// Lifecycle
onMounted(() => {
initTableMode()
if (props.defaultSelected.length > 0) {
setSelectionFromExternal(props.defaultSelected)
}
bindBodyScroll()
})
onBeforeUnmount(() => {
unbindBodyScroll()
if (tableResizeObserver) {
tableResizeObserver.disconnect()
tableResizeObserver = null
}
stopColumnConfigAutoScroll()
})
// Methods
function getDefaultColumnConfigs() {
return normalizedColumns.value.map((column, index) => ({
prop: String(column.prop),
label: column.label,
visible: true,
order: index,
width: column.width,
fixed: column.fixed === true ? 'left' : (column.fixed as 'left' | 'right' | undefined)
}))
}
function applyColumnConfigMap(configs: ColumnConfigItem[]) {
const map: Record<string, ColumnConfigItem> = {}
configs.forEach((item) => {
map[item.prop] = item
})
columnConfigMap.value = map
editableColumnConfigs.value = [...configs].sort((a, b) => a.order - b.order)
}
/** 初始化:优先读更多设置 store,兜底 props.tableMode */
function initTableMode() {
activeTableMode.value = experimentalStore.tableMode
}
/** 切换工作模式(更多设置表单触发):持久化到 store + 重置虚拟滚动状态 */
function handleTableModeChange(mode: 'performance' | 'resource') {
experimentalStore.setTableMode(mode)
resetVirtualScrollState()
}
/** 重置虚拟滚动窗口状态(滚动位置、方向、节流计时器) */
function resetVirtualScrollState() {
virtualScrollTop.value = 0
scrollDirection.value = 'down'
windowScrollDirection.value = 'down'
lastWindowSyncTime = 0
if (scrollSettleTimer !== null) {
clearTimeout(scrollSettleTimer)
scrollSettleTimer = null
}
if (bodyScrollEl.value) bodyScrollEl.value.scrollTop = 0
syncVirtualViewport()
}
// 全局实验性设置中的表格工作模式变化 → 所有 UpperTable 实例即时响应
watch(
() => experimentalStore.tableMode,
(mode) => {
if (!mode || activeTableMode.value === mode) return
activeTableMode.value = mode
resetVirtualScrollState()
}
)
function saveColumnConfig(
configs: ColumnConfigItem[],
options: { defaultColumns?: ColumnConfigItem[] } = {}
) {
if (!columnConfigStorageKey.value) return
const prev = readStoredProfile()
const userId = String(userStore.user?.username || userStore.user?.id || 'unknown')
const roleId = userStore.roleId || 'default'
const payload: TableColumnProfile = {
schemaVersion: props.columnConfigSchemaVersion,
tableId: effectiveTableId.value,
userId,
roleId,
updatedAt: Date.now(),
// 表格名称:便于「设置 → 所有表格字段」中辨认(页面通过 :title 传入)
title: tableTitle.value || prev?.title,
// 默认布局:首次生成配置时快照,供「恢复默认」使用
defaultColumns: options.defaultColumns ?? prev?.defaultColumns,
columns: configs
}
localStorage.setItem(columnConfigStorageKey.value, JSON.stringify(payload))
}
/**
* 在默认列顺序中,从 index 向 step 方向找最近的、已存在 order 的列,返回其 order。
* 用于给「当前 props.columns 中存在、但已保存配置中没有」的列计算插入位置。
*/
function findNeighborColumnOrder(
defaults: ColumnConfigItem[],
index: number,
step: 1 | -1,
knownOrders: Map<string, number>
): number | undefined {
for (let i = index + step; i >= 0 && i < defaults.length; i += step) {
const neighbor = defaults[i]
if (!neighbor) continue
const order = knownOrders.get(neighbor.prop)
if (order !== undefined) return order
}
return undefined
}
/**
* 缺失列插入位置:优先取前后相邻已有列 order 的中间值(用小数占位,后续会被重排为整数),
* 保证列在「临时隐藏 → 重新显示」后回到默认配置的位置,而不是跑到表尾。
*/
function resolveMissingColumnOrder(
defaults: ColumnConfigItem[],
index: number,
knownOrders: Map<string, number>
): number {
const prevOrder = findNeighborColumnOrder(defaults, index, -1, knownOrders)
const nextOrder = findNeighborColumnOrder(defaults, index, 1, knownOrders)
if (prevOrder !== undefined && nextOrder !== undefined) return (prevOrder + nextOrder) / 2
if (prevOrder !== undefined) return prevOrder + 0.5
if (nextOrder !== undefined) return nextOrder - 0.5
return index
}
function buildMergedColumnConfigs(raw?: Partial<ColumnConfigItem>[]) {
const defaults = getDefaultColumnConfigs()
const defaultMap = new Map(defaults.map((item) => [item.prop, item]))
const merged: ColumnConfigItem[] = []
const used = new Set<string>()
;(raw || []).forEach((item, index) => {
if (!item?.prop) return
const prop = String(item.prop)
const base = defaultMap.get(prop)
if (!base) return
used.add(prop)
merged.push({
...base,
visible: item.visible ?? base.visible,
order: Number.isFinite(item.order as number) ? Number(item.order) : index,
width: item.width ?? base.width,
fixed: item.fixed ?? base.fixed
})
})
// 已保存配置中缺失的列(例如被页面按开关临时从 props.columns 移除后又恢复的列)
// 按默认列顺序插回相邻位置,避免被追加到表尾
const knownOrders = new Map<string, number>()
merged.forEach((item) => knownOrders.set(item.prop, item.order))
defaults.forEach((item, index) => {
if (used.has(item.prop)) return
const order = resolveMissingColumnOrder(defaults, index, knownOrders)
merged.push({ ...item, order })
knownOrders.set(item.prop, order)
})
merged.sort((a, b) => a.order - b.order)
return normalizeColumnConfigOrders(merged)
}
function readStoredProfile(): TableColumnProfile | null {
if (!columnConfigStorageKey.value) return null
const raw = localStorage.getItem(columnConfigStorageKey.value)
if (!raw) return null
try {
const parsed = JSON.parse(raw) as TableColumnProfile
if (!parsed || !Array.isArray(parsed.columns)) return null
const storedVersion = parsed.schemaVersion ?? 1
if (storedVersion !== props.columnConfigSchemaVersion) return null
return parsed
} catch {
return null
}
}
function readStoredColumnConfigs() {
return readStoredProfile()?.columns ?? null
}
function rebuildColumnConfig() {
const stored = readStoredProfile()
const merged = buildMergedColumnConfigs(stored?.columns || undefined)
applyColumnConfigMap(merged)
if (props.enableColumnConfig && effectiveTableId.value) {
// 首次(或旧数据缺少 defaultColumns)时,以当前默认列为快照
saveColumnConfig(merged, {
defaultColumns: stored?.defaultColumns || normalizeColumnConfigOrders(getDefaultColumnConfigs())
})
}
}
const tableColumnConfigStore = useTableColumnConfigStore()
// 设置中心「所有表格字段」修改本表配置后,重建列配置(即时生效)
watch(
() => tableColumnConfigStore.versions[effectiveTableId.value || ''],
() => {
if (!props.enableColumnConfig || !effectiveTableId.value) return
rebuildColumnConfig()
}
)
function resolveCopyRawValue(row: any, column: ColumnItem): unknown {
if (typeof column.copyValue === 'function') {
return column.copyValue(row)
}
if (Array.isArray(column.copyValueKeys) && column.copyValueKeys.length) {
for (const key of column.copyValueKeys) {
const val = row?.[key]
const text = getCopyableCellText(val)
if (text) return text
}
return ''
}
return row?.[column.prop || '']
}
function getCopyActionCodes(row: any, column: ColumnItem): string[] {
const prop = String(column.prop || '')
const cacheable = !!row && typeof row === 'object'
if (cacheable) {
const rowCache = copyCodesCache.get(row)
const cached = rowCache?.get(prop)
if (cached) return cached
}
let codes: string[]
if (typeof column.copyValue === 'function') {
const result = column.copyValue(row)
if (Array.isArray(result)) {
codes = result.map((item) => String(item ?? '').trim()).filter(Boolean)
} else {
const text = getCopyableCellText(result)
codes = text ? [text] : []
}
} else {
const raw = resolveCopyRawValue(row, column)
if (column.copyAction === 'copy') {
const text = getCopyableCellText(raw)
codes = text ? [text] : []
} else {
codes = parseMultiValueCodes(raw)
}
}
if (cacheable) {
let rowCache = copyCodesCache.get(row)
if (!rowCache) {
rowCache = new Map()
copyCodesCache.set(row, rowCache)
}
rowCache.set(prop, codes)
}
return codes
}
function getCopyActionTitle(column: ColumnItem) {
if (column.copyAction === 'copyQr') return '点击复制并查看运单号二维码'
return `点击复制${column.label || ''}`
}
/** 运单号列取多个单号(waybillCodes 取值器 → copyValue → 字段值按逗号 / JSON 数组拆分) */
function getWaybillCellCodes(row: any, column: ColumnItem): string[] {
const prop = String(column.prop || '')
const cacheable = !!row && typeof row === 'object'
if (cacheable) {
const cached = waybillCodesCache.get(row)?.get(prop)
if (cached) return cached
}
let codes: string[]
if (typeof column.waybillCodes === 'function') {
const result = column.waybillCodes(row)
codes = Array.isArray(result)
? result.map((item: unknown) => String(item ?? '').trim()).filter(Boolean)
: (getCopyableCellText(result) ? [getCopyableCellText(result)] : [])
} else if (typeof column.copyValue === 'function') {
const result = column.copyValue(row)
if (Array.isArray(result)) {
codes = result.map((item) => String(item ?? '').trim()).filter(Boolean)
} else {
const text = getCopyableCellText(result)
codes = text ? [text] : []
}
} else {
codes = parseMultiValueCodes(row?.[prop])
}
if (cacheable) {
let rowCache = waybillCodesCache.get(row)
if (!rowCache) {
rowCache = new Map()
waybillCodesCache.set(row, rowCache)
}
rowCache.set(prop, codes)
}
return codes
}
async function handleCopyActionClick(code: string, column: ColumnItem) {
const label = String(column.label || '内容').trim() || '内容'
await copyCellText(code, label)
if (column.copyAction === 'copyQr') {
waybillQrCode.value = code
waybillQrVisible.value = true
}
}
function isCopyMultiCollapseEnabled(column: ColumnItem) {
return column.copyMultiCollapse !== false
}
function getMultiCopyCellKey(row: any, column: ColumnItem) {
return `${String(getRowKey(row))}::${String(column.prop || '')}`
}
function isCopyCellExpanded(row: any, column: ColumnItem) {
return expandedMultiCopyCells.value.has(getMultiCopyCellKey(row, column))
}
function toggleCopyCellExpand(row: any, column: ColumnItem) {
const key = getMultiCopyCellKey(row, column)
const next = new Set(expandedMultiCopyCells.value)
if (next.has(key)) {
next.delete(key)
} else {
next.add(key)
}
expandedMultiCopyCells.value = next
}
function getHiddenCopyActionCount(row: any, column: ColumnItem) {
const total = getCopyActionCodes(row, column).length
return Math.max(0, total - 1)
}
function shouldShowCopyCollapseToggle(row: any, column: ColumnItem) {
if (!isCopyMultiCollapseEnabled(column)) return false
return getCopyActionCodes(row, column).length > 1
}
function getVisibleCopyActionCodes(row: any, column: ColumnItem) {
const codes = getCopyActionCodes(row, column)
if (codes.length <= 1 || !isCopyMultiCollapseEnabled(column)) return codes
if (isCopyCellExpanded(row, column)) return codes
return codes.slice(0, 1)
}
function getCopyableCellText(value: unknown) {
if (value === undefined || value === null) return ''
return String(value).trim()
}
function parseMultiValueCodes(raw: unknown): string[] {
if (Array.isArray(raw)) {
return raw.map((item) => String(item ?? '').trim()).filter(Boolean)
}
const text = String(raw ?? '').trim()
if (!text) return []
if (text.startsWith('[') && text.endsWith(']')) {
try {
const parsed = JSON.parse(text)
if (Array.isArray(parsed)) {
return parsed.map((item) => String(item ?? '').trim()).filter(Boolean)
}
} catch {
// ignore invalid json
}
}
if (text.includes(',')) {
return text.split(',').map((item) => item.trim()).filter(Boolean)
}
return [text]
}
// ---------------------------------------------------------------------------
// 超长文本收起(列级开关)
// 用法:列上配置 `textCollapse: true`(默认 30 字符)或 `textCollapse: 数字`(自定义阈值)
// 可选 `textCollapseValue: (row, column, index) => unknown` 自定义取值(默认 formatter 结果 → 行字段原值)
// 表现:文本长度 > 阈值时只显示前 N 个字符,并给出「展开 / 收起」按钮(状态按 行+列 记录)
// ---------------------------------------------------------------------------
/** 默认收起阈值(字符数) */
const DEFAULT_TEXT_COLLAPSE_LIMIT = 30
/** 列的收起阈值;返回 0 表示该列未启用 */
function getTextCollapseLimit(column: ColumnItem): number {
const raw = column.textCollapse
if (raw === undefined || raw === null || raw === false) return 0
if (raw === true) return DEFAULT_TEXT_COLLAPSE_LIMIT
const num = Number(raw)
return Number.isFinite(num) && num > 0 ? Math.floor(num) : 0
}
/** 收起列用于判断长度的完整文本:优先 textCollapseValue,其次 formatter(去 HTML 标签),最后行字段原值 */
function getTextCollapseFullText(row: any, column: ColumnItem, index: number): string {
const prop = String(column.prop || '')
const cacheable = !!row && typeof row === 'object'
if (cacheable) {
const cached = textCollapseCache.get(row)?.get(prop)
if (cached !== undefined) return cached
}
let text = ''
if (typeof column.textCollapseValue === 'function') {
const value = column.textCollapseValue(row, column, index)
text = value === undefined || value === null ? '' : String(value)
} else if (typeof column.formatter === 'function') {
text = getFormattedCell(row, column, row?.[column.prop || ''], index).replace(/<[^>]*>/g, '')
} else {
const value = row?.[column.prop || '']
if (value !== undefined && value !== null) {
text = Array.isArray(value)
? value.map((item) => String(item ?? '').trim()).filter(Boolean).join('|')
: String(value)
}
}
if (cacheable) {
let rowCache = textCollapseCache.get(row)
if (!rowCache) {
rowCache = new Map()
textCollapseCache.set(row, rowCache)
}
rowCache.set(prop, text)
}
return text
}
function getTextCellKey(row: any, column: ColumnItem) {
return `${String(getRowKey(row))}::${String(column.prop || '')}`
}
function isTextCellExpanded(row: any, column: ColumnItem) {
return expandedTextCells.value.has(getTextCellKey(row, column))
}
function toggleTextCellExpand(row: any, column: ColumnItem) {
const key = getTextCellKey(row, column)
const next = new Set(expandedTextCells.value)
if (next.has(key)) {
next.delete(key)
} else {
next.add(key)
}
expandedTextCells.value = next
}
/** 仅当启用收起、文本确实超长(且非自定义 template 列)时才接管渲染,否则退回原有分支 */
function shouldCollapseTextCell(row: any, column: ColumnItem, index: number) {
if (isVirtualSpacerRow(row)) return false
if (typeof column.template === 'function') return false
const limit = getTextCollapseLimit(column)
if (!limit) return false
return getTextCollapseFullText(row, column, index).length > limit
}
/** 收起态只展示前 limit 个字符(不加省略号,靠「展开」按钮提示还有内容),展开态展示全文 */
function getVisibleTextCollapseText(row: any, column: ColumnItem, index: number) {
const text = getTextCollapseFullText(row, column, index)
const limit = getTextCollapseLimit(column)
if (!limit || isTextCellExpanded(row, column) || text.length <= limit) return text
return text.slice(0, limit)
}
async function copyCellText(value: unknown, label: string) {
const text = getCopyableCellText(value)
if (!text) {
ElMessage.warning(`当前行无${label}可复制`)
return
}
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text)
} else {
throw new Error('no clipboard api')
}
ElMessage.success(`${label}已复制到剪贴板`)
} catch {
try {
const textarea = document.createElement('textarea')
textarea.value = text
textarea.setAttribute('readonly', 'readonly')
textarea.style.position = 'fixed'
textarea.style.left = '-9999px'
document.body.appendChild(textarea)
textarea.select()
document.execCommand('copy')
document.body.removeChild(textarea)
ElMessage.success(`${label}已复制到剪贴板`)
} catch {
ElMessage.error('复制失败,请手动复制')
}
}
}
function getDefaultCellTextClass(prop: string | undefined, value: unknown) {
if (prop === 'order_flag' && value !== undefined && value !== null && String(value).trim() !== '') {
return 'order-flag-text order-flag-copyable'
}
if (prop === 'buyer_message' && value !== undefined && value !== null && String(value).trim() !== '') {
return 'buyer-message-text buyer-message-copyable'
}
return ''
}
function truncateBuyerMessage(value: unknown) {
if (value == null) return '—'
const text = String(value).trim()
if (!text) return '—'
const max = 30
return text.length > max ? `${text.slice(0, max)}…` : text
}
async function copyBuyerMessage(value: unknown) {
const text = value != null ? String(value).trim() : ''
if (!text) {
ElMessage.warning('当前订单无买家留言可复制')
return
}
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text)
} else {
throw new Error('no clipboard api')
}
ElMessage.success('买家留言已复制到剪贴板')
} catch {
try {
const textarea = document.createElement('textarea')
textarea.value = text
textarea.setAttribute('readonly', 'readonly')
textarea.style.position = 'fixed'
textarea.style.left = '-9999px'
document.body.appendChild(textarea)
textarea.select()
document.execCommand('copy')
document.body.removeChild(textarea)
ElMessage.success('买家留言已复制到剪贴板')
} catch {
ElMessage.error('复制失败,请手动复制')
}
}
}
function getOrderFlagFullText(value: unknown) {
if (value == null) return ''
return String(value).trim()
}
function getOrderFlagCellText(value: unknown) {
const text = getOrderFlagFullText(value)
if (!text) return '—'
const max = 48
return text.length > max ? `${text.slice(0, max)}…` : text
}
async function copyOrderFlagText(value: unknown) {
const text = getOrderFlagFullText(value)
if (!text) {
ElMessage.warning('当前行无订单标记可复制')
return
}
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text)
} else {
throw new Error('no clipboard api')
}
ElMessage.success('订单标记已复制到剪贴板')
} catch {
try {
const textarea = document.createElement('textarea')
textarea.value = text
textarea.setAttribute('readonly', 'readonly')
textarea.style.position = 'fixed'
textarea.style.left = '-9999px'
document.body.appendChild(textarea)
textarea.select()
document.execCommand('copy')
document.body.removeChild(textarea)
ElMessage.success('订单标记已复制到剪贴板')
} catch {
ElMessage.error('复制失败,请手动复制')
}
}
}
function persistEditableConfigs() {
const normalized = normalizeColumnConfigOrders([...editableColumnConfigs.value])
applyColumnConfigMap(normalized)
saveColumnConfig(normalized)
}
function openColumnConfig() {
editableColumnConfigs.value = normalizeColumnConfigOrders(Object.values(columnConfigMap.value))
settingsInitialSection.value = 'field'
settingsVisible.value = true
}
function onToggleColumnVisible(prop: string, visible: boolean) {
const next = editableColumnConfigs.value.map((item) => {
if (item.prop !== prop) return item
return { ...item, visible }
})
editableColumnConfigs.value = next
persistEditableConfigs()
}
function setFixed(prop: string, position: 'left' | 'right' | false) {
// 先把 fixed 赋上,再将目标列 order 置为最大使其排到对应分区末尾
const next = editableColumnConfigs.value.map((item) => {
if (item.prop !== prop) return item
return { ...item, fixed: position, order: Number.MAX_SAFE_INTEGER - 1 }
})
const normalized = normalizeColumnConfigOrders(next)
applyColumnConfigMap(normalized)
saveColumnConfig(normalized)
}
function moveColumn(prop: string, direction: 'up' | 'down') {
const cfg = editableColumnConfigs.value.find((c) => c.prop === prop)
if (!cfg) return
const { left, mid, right } = partitionColumnConfigsTriplet(editableColumnConfigs.value)
// 查找在哪个分区
let arr: ColumnConfigItem[]
let section: 'left' | 'mid' | 'right'
if (left.some((c) => c.prop === prop)) { arr = left; section = 'left' }
else if (mid.some((c) => c.prop === prop)) { arr = mid; section = 'mid' }
else if (right.some((c) => c.prop === prop)) { arr = right; section = 'right' }
else return
const i = arr.findIndex((c) => c.prop === prop)
if (i === -1) return
const j = direction === 'up' ? i - 1 : i + 1
if (j < 0 || j >= arr.length) return
const tmp = arr[i]!
arr[i] = arr[j]!
arr[j] = tmp
// 排序后各部分内部顺序已正确,重新生成全局 order
const allParts = section === 'left'
? normalizeFromParts(arr, mid, right)
: section === 'right'
? normalizeFromParts(left, mid, arr)
: normalizeFromParts(left, arr, right)
applyColumnConfigMap(allParts)
saveColumnConfig(allParts)
}
function onColumnDragStart(e: DragEvent, item: ColumnConfigItem) {
draggingProp.value = item.prop
}
function runColumnConfigAutoScroll() {
const listEl = columnConfigListRef.value
if (!listEl || dragAutoScrollStep.value === 0) {
dragAutoScrollRaf = null
return
}
listEl.scrollTop += dragAutoScrollStep.value
dragAutoScrollRaf = requestAnimationFrame(runColumnConfigAutoScroll)
}
function startColumnConfigAutoScroll(step: number) {
dragAutoScrollStep.value = step
if (dragAutoScrollStep.value === 0) {
stopColumnConfigAutoScroll()
return
}
if (dragAutoScrollRaf === null) {
dragAutoScrollRaf = requestAnimationFrame(runColumnConfigAutoScroll)
}
}
function stopColumnConfigAutoScroll() {
dragAutoScrollStep.value = 0
if (dragAutoScrollRaf !== null) {
cancelAnimationFrame(dragAutoScrollRaf)
dragAutoScrollRaf = null
}
}
function onColumnDragOver(e: DragEvent, item: ColumnConfigItem) {
if (!draggingProp.value) return
if (draggingProp.value === item.prop) return
const sourceCfg = editableColumnConfigs.value.find((c) => c.prop === draggingProp.value)
if (!sourceCfg) return
// 只允许在同一分区内拖动
const { left, mid, right } = partitionColumnConfigsTriplet(editableColumnConfigs.value)
const inLeft = left.some((c) => c.prop === draggingProp.value)
const inRight = right.some((c) => c.prop === draggingProp.value)
const targetInLeft = left.some((c) => c.prop === item.prop)
const targetInRight = right.some((c) => c.prop === item.prop)
if (inLeft !== targetInLeft || inRight !== targetInRight) return
dragOverProp.value = item.prop
const listEl = columnConfigListRef.value
if (!listEl) return
const rect = listEl.getBoundingClientRect()
const threshold = 56
const maxStep = 8
let step = 0
if (e.clientY < rect.top + threshold) {
const ratio = (rect.top + threshold - e.clientY) / threshold
step = -Math.max(2, Math.min(maxStep, Math.round(ratio * maxStep)))
} else if (e.clientY > rect.bottom - threshold) {
const ratio = (e.clientY - (rect.bottom - threshold)) / threshold
step = Math.max(2, Math.min(maxStep, Math.round(ratio * maxStep)))
}
startColumnConfigAutoScroll(step)
}
function onColumnDrop(target: ColumnConfigItem) {
const sourceProp = draggingProp.value
if (!sourceProp || sourceProp === target.prop) {
onColumnDragEnd()
return
}
const sourceCfg = editableColumnConfigs.value.find((c) => c.prop === sourceProp)
if (!sourceCfg) {
onColumnDragEnd()
return
}
const { left, mid, right } = partitionColumnConfigsTriplet(editableColumnConfigs.value)
// 找到源和目标所在分区
let arr: ColumnConfigItem[]
if (left.some((c) => c.prop === sourceProp)) arr = left
else if (mid.some((c) => c.prop === sourceProp)) arr = mid
else if (right.some((c) => c.prop === sourceProp)) arr = right
else { onColumnDragEnd(); return }
// 目标必须在同一个分区
if (!arr.some((c) => c.prop === target.prop)) { onColumnDragEnd(); return }
const sourceIndex = arr.findIndex((item) => item.prop === sourceProp)
const targetIndex = arr.findIndex((item) => item.prop === target.prop)
if (sourceIndex === -1 || targetIndex === -1) {
onColumnDragEnd()
return
}
const sourceItem = arr[sourceIndex]
if (!sourceItem) {
onColumnDragEnd()
return
}
arr.splice(sourceIndex, 1)
arr.splice(targetIndex, 0, sourceItem)
const next = normalizeFromParts(left, mid, right)
applyColumnConfigMap(next)
saveColumnConfig(next)
onColumnDragEnd()
}
function onColumnDragEnd() {
draggingProp.value = ''
dragOverProp.value = ''
stopColumnConfigAutoScroll()
}
function resetColumnConfig() {
const defaults = normalizeColumnConfigOrders(getDefaultColumnConfigs())
applyColumnConfigMap(defaults)
saveColumnConfig(defaults)
ElMessage.success('已恢复默认字段配置')
}
/** 方案⑧:formatter 结果按行缓存(WeakMap,行对象生命周期自动回收),避免滚动窗口切换时重复计算 */
const formatterCache = new WeakMap<object, Map<string, string>>()
function getFormattedCell(row: any, column: any, value: any, index: number): string {
const fn = column?.formatter
if (typeof fn !== 'function') return ''
if (!row || typeof row !== 'object') {
return String(fn(row, column, value, index) ?? '')
}
let rowCache = formatterCache.get(row)
if (!rowCache) {
rowCache = new Map()
formatterCache.set(row, rowCache)
}
const key = String(column.prop || '')
if (rowCache.has(key)) return rowCache.get(key)!
const result = String(fn(row, column, value, index) ?? '')
rowCache.set(key, result)
return result
}
function getRowKey(row: any) {
if (isVirtualSpacerRow(row)) {
return `virtual-${row.__virtualSpacerType}`
}
if (row && typeof row === 'object') {
const cached = rowKeyCache.get(row)
if (cached !== undefined) return cached
const key = typeof props.rowKey === 'function' ? props.rowKey(row) : row[props.rowKey]
rowKeyCache.set(row, key)
return key
}
return typeof props.rowKey === 'function' ? props.rowKey(row) : row?.[props.rowKey]
}
function createVirtualSpacerRow(type: 'top' | 'bottom', height: number): VirtualSpacerRow {
return {
__virtualSpacer: true,
__virtualSpacerType: type,
__virtualSpacerHeight: height
}
}
function isVirtualSpacerRow(row: any): row is VirtualSpacerRow {
return !!row && row.__virtualSpacer === true
}
const EMPTY_ROW_STYLE: Record<string, string> = {}
function getRowClassName({ row }: { row: any }) {
if (isVirtualSpacerRow(row)) return 'virtual-spacer-row'
if (typeof props.rowClassName === 'function') {
return props.rowClassName({ row }) || ''
}
if (typeof props.rowClassName === 'string') return props.rowClassName
return ''
}
function getRowStyle({ row }: { row: any }) {
if (!isVirtualSpacerRow(row)) return EMPTY_ROW_STYLE
return {
height: `${row.__virtualSpacerHeight}px`
}
}
/** 测量可视区数据行的真实行高(中位数),用于修正 spacer 占位高度 */
function measureRenderedRowHeight() {
if (!shouldUseVirtual.value) return
const wrap = bodyScrollEl.value
if (!wrap) return
const rowEls = wrap.querySelectorAll<HTMLElement>('.el-table__body tbody tr.el-table__row')
if (!rowEls.length) return
const heights: number[] = []
rowEls.forEach((tr) => {
if (tr.classList.contains('virtual-spacer-row')) return
const h = tr.getBoundingClientRect().height
if (h > 0) heights.push(h)
})
if (!heights.length) return
heights.sort((a, b) => a - b)
const median = heights[Math.floor(heights.length / 2)] || 0
if (!median) return
// 只吸收 > 1px 的偏差:亚像素差异不值得再触发一次全量重算
if (measuredRowHeight.value === 0 || Math.abs(median - measuredRowHeight.value) > 1) {
measuredRowHeight.value = Math.round(median * 100) / 100
}
}
/** 兜底:实际行高与占位高度始终对不上时,强制固定行高(CSS)打断滚动抖动循环 */
function enableFixedRowHeightFallback() {
if (virtualOscillating.value) return
virtualOscillating.value = true
measuredRowHeight.value = assumedRowHeight.value
console.warn('[UpperTable] 检测到虚拟滚动高度抖动,已启用固定行高兜底渲染(长文本改为单行省略)')
// CSS 固定行高生效后会改变内容总高度,立即再对齐一次 scrollTop
nextTick(() => {
scheduleScrollReconcile()
})
}
/**
* 渲染后校正滚动位置。
* el-table 的 :data 被替换后若内容总高度变化,浏览器会改写 scrollTop,
* 进而触发 scroll 事件 → 再次更新窗口 → 再次改写,形成"滚动条上下弹、内容不更新"的死循环。
* 这里以浏览器最终位置为准对齐窗口,使下一轮 scroll 事件不再触发重渲染;连续 3 次仍被改写则兜底。
*/
function scheduleScrollReconcile() {
nextTick(() => {
if (reconcileRaf !== null) cancelAnimationFrame(reconcileRaf)
reconcileRaf = requestAnimationFrame(() => {
reconcileRaf = null
const wrap = bodyScrollEl.value
if (!wrap || !shouldUseVirtual.value) return
const actual = wrap.scrollTop || 0
if (Math.abs(actual - virtualScrollTop.value) <= 1) {
reconcilePasses = 0
return
}
reconcilePasses += 1
if (reconcilePasses >= 3) {
reconcilePasses = 0
enableFixedRowHeightFallback()
return
}
virtualScrollTop.value = actual
if (reconcileResetTimer !== null) clearTimeout(reconcileResetTimer)
reconcileResetTimer = setTimeout(() => {
reconcileResetTimer = null
reconcilePasses = 0
}, 800)
})
})
}
/** 渲染结束后测量行高(测量结果会反过来影响 spacer,故只在偏差 > 1px 时更新) */
function scheduleRowHeightMeasure() {
nextTick(() => {
requestAnimationFrame(() => {
measureRenderedRowHeight()
})
})
}
/** 视口高度只在 ResizeObserver / 首次绑定时读取,滚动中不再读取 clientHeight(避免每帧强制 reflow) */
function updateViewportHeight() {
const height = bodyScrollEl.value?.clientHeight || 0
if (Math.abs(height - virtualViewportHeight.value) > 1) virtualViewportHeight.value = height
}
/** 上次滚动中预取的时间戳(节流用,避免连续重建把主线程占满) */
let lastPrefetchAt = 0
/**
* 滚动中预取:视口一旦脱离"已渲染窗口",立即(节流)补一次窗口,
* 避免快速向上/向下滚动时出现整片白屏、要等停止后才加载数据。
* 只有真正越界才触发,正常小步滚动仍在 buffer 内,不会增加重建次数。
*/
function maybePrefetchWindow(top: number) {
if (!shouldUseVirtual.value) return
const rowHeight = virtualRowHeight.value
const viewportHeight = virtualViewportHeight.value
if (!rowHeight || !viewportHeight) return
const start = virtualStartIndex.value
const end = virtualEndIndex.value
const firstVisible = Math.floor(top / rowHeight)
const lastVisible = Math.ceil((top + viewportHeight) / rowHeight)
// 视口仍完整落在已渲染窗口内(预留 1 行余量)→ 无需预取
if (firstVisible >= start + 1 && lastVisible <= end - 1) return
const now = Date.now()
const minInterval = activeTableMode.value === 'performance' ? 150 : 300
if (now - lastPrefetchAt < minInterval) return
lastPrefetchAt = now
windowScrollDirection.value = scrollDirection.value
virtualScrollTop.value = top
}
function handleBodyScroll() {
if (scrollRaf !== null) return
scrollRaf = requestAnimationFrame(() => {
scrollRaf = null
if (!bodyScrollEl.value) return
const top = bodyScrollEl.value.scrollTop || 0
// 检测滚动方向:向上滚动时顶部 buffer 加倍,减少向上滚动"真空期"(方案⑥)
if (top > virtualScrollTop.value) scrollDirection.value = 'down'
else if (top < virtualScrollTop.value) scrollDirection.value = 'up'
// 抖动校正后 scrollTop 与窗口一致,直接跳过,避免"渲染 → 改写 scrollTop → 再渲染"死循环
if (Math.abs(top - virtualScrollTop.value) < 1) return
// 滚动中越界预取(否则快速滚动时会白屏,直到停止后才补数据)
maybePrefetchWindow(top)
// 方案⑨+优化:两种模式滚动中都冻结窗口(避免每次滚动触发 el-table :data 全量重算 ~300ms 卡顿),
// 停止滚动后统一更新。performance 用更短 debounce(60ms)+ 大 buffer 更快到位。
const settleDelay = activeTableMode.value === 'performance' ? 60 : 120
if (scrollSettleTimer !== null) clearTimeout(scrollSettleTimer)
scrollSettleTimer = setTimeout(() => {
scrollSettleTimer = null
if (!bodyScrollEl.value) return
// 方向缓冲区只在窗口真正更新时生效:滚动中翻转方向不会闪变渲染行数,避免整表重建
windowScrollDirection.value = scrollDirection.value
virtualScrollTop.value = bodyScrollEl.value.scrollTop || 0
// 停止后重置预取节流,下一次滚动可以立即补窗
lastPrefetchAt = 0
// 行高已在绑定/数据变化/尺寸变化时实测,这里不再测量(getBoundingClientRect 会强制 layout)
scheduleScrollReconcile()
}, settleDelay)
})
}
function unbindBodyScroll() {
if (scrollRaf !== null) {
cancelAnimationFrame(scrollRaf)
scrollRaf = null
}
if (reconcileRaf !== null) {
cancelAnimationFrame(reconcileRaf)
reconcileRaf = null
}
if (reconcileResetTimer !== null) {
clearTimeout(reconcileResetTimer)
reconcileResetTimer = null
}
if (scrollSettleTimer !== null) {
clearTimeout(scrollSettleTimer)
scrollSettleTimer = null
}
if (!bodyScrollEl.value) return
bodyScrollEl.value.removeEventListener('scroll', handleBodyScroll)
}
/** 监听表格滚动区尺寸:窗口缩放 / 上下分栏拖拽时同步视口高度并重测行高 */
function bindResizeObserver(tableEl: HTMLElement) {
if (typeof ResizeObserver === 'undefined') return
const target = tableEl.querySelector('.el-table__body-wrapper') as HTMLElement | null
if (!target) return
if (!tableResizeObserver) {
tableResizeObserver = new ResizeObserver(() => {
updateViewportHeight()
scheduleRowHeightMeasure()
})
}
tableResizeObserver.disconnect()
tableResizeObserver.observe(target)
}
function bindBodyScroll() {
nextTick(() => {
unbindBodyScroll()
if (!tableRef.value?.$el) return
const tableEl = tableRef.value.$el as HTMLElement
const scrollWrap = (tableEl.querySelector('.el-table__body-wrapper .el-scrollbar__wrap')
|| tableEl.querySelector('.el-scrollbar__wrap')) as HTMLElement | null
bodyScrollEl.value = scrollWrap
if (!bodyScrollEl.value) return
bodyScrollEl.value.addEventListener('scroll', handleBodyScroll, { passive: true })
bindResizeObserver(tableEl)
updateViewportHeight()
handleBodyScroll()
scheduleRowHeightMeasure()
scheduleScrollReconcile()
})
}
function syncVirtualViewport() {
nextTick(() => {
// 数据源变化(翻页/新数据)时重置滚动位置,避免虚拟滚动窗口错位
virtualScrollTop.value = 0
if (bodyScrollEl.value) {
bodyScrollEl.value.scrollTop = 0
}
bindBodyScroll()
})
}
/** 仅重新绑定滚动容器(loading / 列显示变化等),不重置滚动位置 */
function rebindVirtualViewport() {
nextTick(() => {
bindBodyScroll()
})
}
function isRowSelected(row: any) {
const rowKey = getRowKey(row)
return selectedRowKeys.value.has(rowKey)
}
function toggleRowSelection(row: any, selected: boolean | null = null) {
if (isVirtualSpacerRow(row)) return
const rowKey = getRowKey(row)
const currentlySelected = selectedRowKeys.value.has(rowKey)
const shouldSelect = selected !== null ? selected : !currentlySelected
if (shouldSelect && !currentlySelected) {
selectedRowKeys.value.add(rowKey)
selectedRows.value.push(row)
emit('row-selection-change', {
row,
rowKey,
selected: true,
selectedRows: [...selectedRows.value],
selectedKeys: [...selectedRowKeys.value]
})
} else if (!shouldSelect && currentlySelected) {
selectedRowKeys.value.delete(rowKey)
const index = selectedRows.value.findIndex((r: any) => getRowKey(r) === rowKey)
if (index !== -1) {
selectedRows.value.splice(index, 1)
}
emit('row-selection-change', {
row,
rowKey,
selected: false,
selectedRows: [...selectedRows.value],
selectedKeys: [...selectedRowKeys.value]
})
}
emit('select-all-change', {
isSelectAll: isAllSelected.value,
isAllSelectedInView: isAllSelectedInView.value,
selectedRows: [...selectedRows.value],
selectedKeys: [...selectedRowKeys.value],
totalSelectableRows: selectableRows.value.length
})
setTimeout(() => {
checkboxUpdateKey.value = Date.now()
}, 10)
}
function toggleAllSelection() {
if (props.data.length === selectedRows.value.length) {
clearSelection()
} else {
const allSelectableRows = selectableRows.value
selectedRows.value = [...allSelectableRows]
selectedRowKeys.value.clear()
allSelectableRows.forEach((row: any) => {
selectedRowKeys.value.add(getRowKey(row))
})
emit('select-all-change', {
isSelectAll: true,
isAllSelectedInView: isAllSelectedInView.value,
selectedRows: [...selectedRows.value],
selectedKeys: [...selectedRowKeys.value],
totalSelectableRows: allSelectableRows.length
})
}
setTimeout(() => {
checkboxUpdateKey.value = Date.now()
}, 10)
}
function clearSelection() {
selectedRows.value = []
selectedRowKeys.value.clear()
emit('selection-change', [])
emit('select-all-change', {
isSelectAll: false,
isAllSelectedInView: false,
selectedRows: [],
selectedKeys: [],
totalSelectableRows: selectableRows.value.length
})
}
function getSelection() {
return [...selectedRows.value]
}
function getSelectionKeys() {
return [...selectedRowKeys.value]
}
function isSelected(row: any) {
const rowKey = getRowKey(row)
return selectedRowKeys.value.has(rowKey)
}
function setSelectionFromExternal(rows: any[]) {
// Logic to sync external selection
// This was missing in the original code snippet provided in Read tool for methods section
// Assuming it sets selectedRows and selectedRowKeys
selectedRows.value = [...rows]
selectedRowKeys.value.clear()
rows.forEach(row => {
selectedRowKeys.value.add(getRowKey(row))
})
}
function handleCurrentChange(currentRow: any, oldCurrentRow: any) {
if (isVirtualSpacerRow(currentRow)) return
emit('current-change', currentRow, oldCurrentRow)
}
function handleRowClick(row: any, column: any, event: any) {
if (isVirtualSpacerRow(row)) return
const target = event.target
const isCheckbox = target.classList.contains('el-checkbox') ||
target.closest('.el-checkbox') ||
target.classList.contains('custom-selection-cell') ||
target.closest('.custom-selection-cell')
if (!isCheckbox) {
emit('row-click', row, column, event)
}
}
function handleRowContextMenu(row: any, column: any, event: any) {
if (isVirtualSpacerRow(row)) return
emit('row-contextmenu', row, column, event)
}
function handleSortChange({ column, prop, order }: any) {
emit('sort-change', { column, prop, order })
}
function handlePageSizeChange(size: number) {
emit('page-size-change', size)
}
function handlePageChange(page: number) {
emit('page-change', page)
}
function handleRefresh() {
emit('refresh')
}
function getTableRef() {
return tableRef.value
}
function setCurrentRow(row: any) {
if (tableRef.value) {
tableRef.value.setCurrentRow(row)
}
}
function clearSort() {
if (tableRef.value) {
tableRef.value.clearSort()
}
}
function clearFilter(columnKey: string) {
if (tableRef.value) {
tableRef.value.clearFilter(columnKey)
}
}
function getSummaries(param: { columns: any, data: any }) {
const { columns, data } = param
const sums: string[] = []
columns.forEach((column: any, index: number) => {
if (index === 0) {
sums[index] = '总计'
return
}
const values = data.map((item: any) => Number(item[column.property]))
if (!values.every((value: number) => isNaN(value))) {
sums[index] = values.reduce((prev: number, curr: number) => {
const value = Number(curr)
if (!isNaN(value)) {
return prev + curr
} else {
return prev
}
}, 0)
sums[index] += ' 元'
} else {
sums[index] = 'N/A'
}
})
return sums
}
// Expose methods
defineExpose({
getSelection,
getSelectionKeys,
toggleRowSelection,
toggleAllSelection,
openColumnConfig,
clearSelection,
getTableRef,
setCurrentRow,
clearSort,
clearFilter,
getSummaries
})
watch(
() => [props.tableSize, props.showHeader, props.showPagination],
() => {
syncVirtualViewport()
},
{ deep: true }
)
// loading 只代表数据请求状态,不应把用户已滚动到的位置重置回顶部
watch(
() => props.loading,
() => {
rebindVirtualViewport()
}
)
// 虚拟窗口变化后校正 scrollTop,打断"渲染 → 浏览器改写 scrollTop → 再渲染"的死循环
watch([virtualScrollTop, measuredRowHeight], () => {
scheduleScrollReconcile()
})
</script>
<style scoped>
/* 表头居中 */
:deep(.el-table__header-wrapper th .cell) {
text-align: center;
}
/* 基础样式 */
.upper-table-container {
display: flex;
flex-direction: column;
background: #fff;
border-radius: 4px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
overflow: hidden;
position: relative;
/* 支持弹性高度:允许在 flex 父容器中自动伸缩 */
flex: 1 1 auto;
min-height: 0;
height: 100%;
}
.table-container {
/* 移除固定高度,弹性填满 upper-table-container 剩余空间 */
flex: 1 1 auto;
min-height: 0;
overflow: auto;
z-index: 9;
}
/* 禁止浏览器的滚动锦定:虚拟滚动会不断增删 spacer 行,
锚定机制会在 DOM 变更后自动改写 scrollTop,与窗口计算相互打架导致滚动条来回弹 */
.upper-table-container :deep(.el-table__body-wrapper .el-scrollbar__wrap) {
overflow-anchor: none;
}
/* 虚拟滚动高度抖动兜底:强制行高与 spacer 占位一致,并单行省略避免内容撑高 */
.upper-table-container.is-fixed-row-height {
--ut-fixed-row-height: 32px;
}
.upper-table-container.is-fixed-row-height.default {
--ut-fixed-row-height: 41px;
}
.upper-table-container.is-fixed-row-height.large {
--ut-fixed-row-height: 49px;
}
.upper-table-container.is-fixed-row-height :deep(.el-table__body-wrapper .el-table__row) {
height: var(--ut-fixed-row-height);
}
.upper-table-container.is-fixed-row-height :deep(.el-table__body-wrapper .el-table__row .cell) {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.pagination-container {
padding: 5px 10px;
border-top: 1px solid #e8e8e8;
background: #fff;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
flex-shrink: 0;
}
.pagination-info {
font-size: 12px;
color: #606266;
white-space: nowrap;
}
/* Ensure pagination elements don't disappear on small screens/containers */
.pagination-container :deep(.el-pagination__sizes),
.pagination-container :deep(.el-pagination__jump),
.pagination-container :deep(.el-pagination__total) {
display: inline-flex !important;
margin-right: 8px;
}
.pagination-container :deep(.el-pagination) {
flex-wrap: wrap;
justify-content: flex-end;
--el-pagination-button-width: 28px;
--el-pagination-button-height: 28px;
}
.pagination-container :deep(.el-select--small) {
width: 80px;
}
.pagination-container :deep(.el-input__wrapper) {
padding: 0 4px;
}
.empty-table {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 200px;
color: #999;
}
.empty-table p {
margin: 0;
font-size: 14px;
margin-top: 10px;
}
/* 自定义选择列样式 */
.custom-selection-header {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
cursor: pointer;
}
.custom-selection-cell {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
cursor: pointer;
}
/* 防止复选框点击事件冒泡 */
.custom-selection-header :deep(.el-checkbox),
.custom-selection-cell :deep(.el-checkbox) {
margin: 0;
pointer-events: none; /* 让父元素处理点击事件 */
}
/* native 勾选列(type="selection"):尺寸对齐自定义勾选列,避免树形表格行高 / 勾选框比其它列表页小一圈 */
:deep(.el-table-column--selection .cell) {
display: flex;
align-items: center;
justify-content: center;
height: 32px;
padding: 0;
}
:deep(.el-table-column--selection .el-checkbox) {
height: auto;
margin: 0;
}
:deep(.el-table-column--selection .el-checkbox__inner) {
width: 14px;
height: 14px;
}
:deep(.virtual-spacer-row td) {
padding: 0 !important;
border: 0 !important;
background: transparent !important;
}
.virtual-spacer-cell {
display: block;
width: 100%;
height: 100%;
pointer-events: none;
}
.column-config-toolbar {
display: flex;
gap: 8px;
margin-bottom: 12px;
align-items: center;
}
.field-section-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
padding: 4px 0 8px 12px;
}
.field-section-title {
font-size: 13px;
line-height: 20px;
font-weight: 600;
color: #303133;
}
.field-section-desc {
margin-top: 4px;
font-size: 12px;
line-height: 18px;
color: #909399;
}
.table-mode-label {
font-size: 13px;
color: #606266;
white-space: nowrap;
}
.column-config-list {
display: flex;
flex-direction: row;
gap: 0;
max-height: 440px;
border: 1px solid #ebeef5;
border-radius: 4px;
overflow: hidden;
}
.column-config-section {
flex: 1;
display: flex;
flex-direction: column;
min-width: 0;
border-right: 1px solid #e4e7ed;
}
.column-config-section:last-child {
border-right: none;
}
.column-config-section-body {
flex: 1;
overflow-y: auto;
overscroll-behavior: contain;
}
.column-config-section-title {
padding: 5px 8px 4px;
font-size: 12px;
color: #606266;
background: #fafafa;
font-weight: 600;
border-bottom: 1px solid #ebeef5;
white-space: nowrap;
flex-shrink: 0;
}
.column-config-section--fixed-left .column-config-section-title {
color: #409eff;
}
.column-config-section--fixed-right .column-config-section-title {
color: #67c23a;
}
.column-config-item {
display: flex;
align-items: center;
justify-content: space-between;
padding: 3px 6px;
border-bottom: 1px solid #f2f3f5;
gap: 4px;
}
.column-config-section .column-config-item:last-child {
border-bottom: none;
}
.column-config-item.is-fixed-column {
background: #f5f7fa;
}
.column-config-section--fixed-left .column-config-item.is-fixed-column {
border-left: 3px solid #409eff;
}
.column-config-section--fixed-right .column-config-item.is-fixed-column {
border-right: 3px solid #67c23a;
}
.column-config-item.is-draggable {
cursor: move;
}
.column-config-item.is-drag-over {
background: #f0f9ff;
border-top: 1px dashed #409eff;
}
.column-config-empty {
display: flex;
align-items: center;
justify-content: center;
flex: 1;
min-height: 60px;
color: #c0c4cc;
font-size: 12px;
user-select: none;
}
.drag-handle--locked {
color: #dcdfe6;
cursor: not-allowed;
user-select: none;
}
.column-config-actions {
display: flex;
align-items: center;
gap: 1px;
flex-shrink: 0;
flex-wrap: wrap;
justify-content: flex-end;
}
.column-config-actions .cfg-fix-btn,
.column-config-actions .cfg-move-btn {
padding: 2px 2px;
font-size: 10px;
line-height: 1;
font-weight: 700;
}
.column-config-actions--fixed {
flex-shrink: 0;
}
.column-config-fixed-hint {
font-size: 12px;
color: #909399;
padding: 0 10px;
user-select: none;
}
.column-config-main {
display: flex;
align-items: center;
gap: 4px;
flex: 1;
min-width: 0;
}
.column-config-main .el-checkbox {
font-size: 12px;
white-space: nowrap;
}
.drag-handle {
color: #909399;
font-size: 14px;
line-height: 1;
user-select: none;
}
.order-flag-text {
color: #f56c6c;
font-weight: 600;
}
.order-flag-copyable {
cursor: pointer;
}
.buyer-message-text {
color: #409eff;
}
.buyer-message-copyable {
cursor: pointer;
}
.click-copy-list {
display: flex;
flex-direction: column;
gap: 2px;
align-items: center;
width: 100%;
}
.click-copy-toggle {
border: none;
background: none;
padding: 0;
margin: 0;
color: var(--el-text-color-secondary);
font-size: 12px;
line-height: 1.4;
cursor: pointer;
flex-shrink: 0;
&:hover {
color: var(--el-color-primary);
}
&:focus-visible {
outline: 2px solid var(--el-color-primary-light-3);
outline-offset: 2px;
border-radius: 2px;
}
}
.click-copy-link {
color: var(--el-color-primary);
cursor: pointer;
word-break: break-all;
line-height: 1.4;
max-width: 100%;
&:hover {
color: var(--el-color-primary-dark-2);
}
&:focus-visible {
outline: 2px solid var(--el-color-primary-light-3);
outline-offset: 2px;
border-radius: 2px;
}
}
/* 超长文本收起(列级 textCollapse) */
.text-collapse-cell {
display: flex;
flex-direction: column;
gap: 2px;
align-items: center;
width: 100%;
}
.text-collapse-text {
word-break: break-all;
line-height: 1.4;
max-width: 100%;
}
.text-collapse-toggle {
border: none;
background: none;
padding: 0;
margin: 0;
color: var(--el-color-primary);
font-size: 12px;
line-height: 1.4;
cursor: pointer;
flex-shrink: 0;
&:hover {
color: var(--el-color-primary-dark-2);
}
&:focus-visible {
outline: 2px solid var(--el-color-primary-light-3);
outline-offset: 2px;
border-radius: 2px;
}
}
/* 表格尺寸样式 */
.upper-table-container.small :deep(.el-table) {
font-size: 12px;
}
.upper-table-container.small :deep(.el-table td),
.upper-table-container.small :deep(.el-table th) {
padding: 6px 0;
}
.upper-table-container.large :deep(.el-table) {
font-size: 14px;
}
.upper-table-container.large :deep(.el-table td),
.upper-table-container.large :deep(.el-table th) {
padding: 12px 0;
}
/* 响应式调整 */
@media (max-width: 768px) {
.table-header {
flex-direction: column;
align-items: flex-start;
gap: 12px;
}
.header-right {
width: 100%;
justify-content: flex-end;
}
}
</style>