cwg-tabel.vue 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. <template>
  2. <view>
  3. <!-- 统一表格容器,根据屏幕宽度自适应 -->
  4. <view class="table-container" :class="{ 'mobile-table': isMobile }">
  5. <uni-table :type="selectionType" :border="false" @selection-change="handleSelectionChange" emptyText="">
  6. <!-- 表头:根据设备类型显示不同的列 -->
  7. <uni-tr class="table-header">
  8. <uni-th v-for="column in displayColumns" :key="column.prop" :align="column.align || 'center'"
  9. :width="column.width || '200'" :class="[headerClass, { sortable: column.sortable }]"
  10. :style="getHeaderStyle(column)" @click="column.sortable && handleSort(column)">
  11. <view class="header-content">
  12. {{ column.label }}
  13. <view v-if="column.sortable" class="sort-icon">
  14. <uni-icons :type="getSortIcon(column)" :size="14" color="#999" />
  15. </view>
  16. </view>
  17. </uni-th>
  18. </uni-tr>
  19. <!-- 表格主体 -->
  20. <template v-for="(row, rowIndex) in tableData" :key="rowIndex">
  21. <uni-tr>
  22. <!-- 数据列:根据设备类型动态渲染 -->
  23. <uni-td v-for="column in displayColumns" :key="column.prop" :align="column.align || 'center'"
  24. :class="getCellClass(column, row)" :style="getCellStyle(column, row)"
  25. @click="openRowDetail(row)">
  26. <template v-if="column.slot">
  27. <slot :name="column.slot" :row="row" :column="column" :index="rowIndex">
  28. {{ row[column.prop] }}
  29. </slot>
  30. </template>
  31. <uni-tag v-else-if="column.type === 'tag'" :text="formatTagText(row[column.prop], column)"
  32. :type="formatTagType(row[column.prop], column)" size="small" />
  33. <view v-else-if="column.type === 'file'">
  34. <cwg-file :path="row[column.prop]" />
  35. </view>
  36. <view v-else-if="column.type === 'note'">
  37. <text>{{ getNoteText(row, locale, userStore) }}</text>
  38. </view>
  39. <view v-else-if="column.type === 'action'" class="action-wrapper">
  40. <view class="action-list">
  41. <template v-for="(item, idx) in getVisibleActions(column.menuList, row)" :key="idx">
  42. <text v-if="actionExpanded[`${rowIndex}-${column.prop}`] || idx < 2"
  43. class="action-btn" @click.stop="item.btnClick && item.btnClick(row)">
  44. {{ item.label || item.text || item.name }}
  45. </text>
  46. </template>
  47. <text v-if="getVisibleActions(column.menuList, row).length > 2"
  48. class="action-toggle-btn" @click.stop="toggleAction(rowIndex, column.prop)">
  49. {{ actionExpanded[`${rowIndex}-${column.prop}`] ? '隐藏' : '更多' }}
  50. </text>
  51. </view>
  52. </view>
  53. <cwg-icon v-else-if="column.type === 'more'" name="crm-chevron-down"
  54. class="crm-chevron-down" :size="16" color="#007" />
  55. <template v-else>
  56. {{ formatCellValue(row[column.prop], column, row) }}
  57. </template>
  58. </uni-td>
  59. </uni-tr>
  60. <!-- 桌面端展开行(仅当非移动端且行展开时显示) -->
  61. <uni-tr v-if="!isMobile && expandedRows[rowIndex]" class="expand-row">
  62. <uni-td :colspan="columnSpan" class="expand-cell">
  63. <slot name="expand" :row="row" :rowIndex="rowIndex">
  64. <view class="default-expand-content">
  65. <text class="no-content">暂无展开内容</text>
  66. </view>
  67. </slot>
  68. </uni-td>
  69. </uni-tr>
  70. </template>
  71. <!-- 总计行 -->
  72. <uni-tr v-if="showSummary && tableData.length !== 0" class="summary-row">
  73. <uni-td v-for="(column, index) in displayColumns" :key="'summary-' + column.prop"
  74. :align="column.align || 'center'" class="summary-cell"
  75. :style="getCellStyle(column, currentSummaryData)">
  76. <!-- 当有 summaryMethod 时,按照返回的数组直接渲染 -->
  77. <template v-if="props.summaryMethod">
  78. <text>{{ computedSummaryRow[index] !== undefined ? computedSummaryRow[index] : '' }}</text>
  79. </template>
  80. <template v-else>
  81. <!-- 特定列的总计自定义插槽,例如 #summary-volume="{ row }" -->
  82. <template v-if="$slots['summary-' + column.prop]">
  83. <slot :name="'summary-' + column.prop" :row="currentSummaryData" :column="column"
  84. :index="index"></slot>
  85. </template>
  86. <!-- 如果没有特定插槽,尝试常规渲染 -->
  87. <template v-else>
  88. <template
  89. v-if="currentSummaryData && currentSummaryData[column.prop] !== undefined && currentSummaryData[column.prop] !== null">
  90. <!-- 如果有常规插槽,并且总计数据里有该字段的值,则复用常规插槽渲染 -->
  91. <slot v-if="column.slot" :name="column.slot" :row="currentSummaryData"
  92. :column="column" :index="index">
  93. {{ currentSummaryData[column.prop] }}
  94. </slot>
  95. <!-- 否则使用格式化函数 -->
  96. <text v-else>{{ formatCellValue(currentSummaryData[column.prop], column,
  97. currentSummaryData) }}</text>
  98. </template>
  99. <!-- 如果总计数据里没有该字段的值,第一列显示总计文本,其他留空 -->
  100. <text v-else>{{ index === 0 ? summaryText : '' }}</text>
  101. </template>
  102. </template>
  103. </uni-td>
  104. </uni-tr>
  105. </uni-table>
  106. </view>
  107. <view class="table-loading-mask">
  108. <uni-loading v-if="loading" />
  109. </view>
  110. <!-- 空状态 -->
  111. <view v-if="!loading && tableData.length === 0" style="width: 100%;">
  112. <cwg-empty-state />
  113. </view>
  114. <!-- 分页 -->
  115. <view class="pagination-container" v-if="showPagination && tableData.length > 0">
  116. <!-- <view class="pagination-info">
  117. <text>共 {{ pagination.total }} 条记录</text>
  118. <view v-if="showPageSize" class="page-size-select">
  119. <text>每页显示</text>
  120. <picker @change="handlePageSizeChange" :value="pageSizeIndex" :range="pageSizes">
  121. <view class="page-size-value">{{ pagination.pageSize }}条/页</view>
  122. </picker>
  123. </view>
  124. </view> -->
  125. <view class="pagination">
  126. <view class="page-item prev" :class="{ disabled: pagination.current === 1 }"
  127. @click="handlePageChange('prev')">
  128. <uni-icons type="arrowright" size="16" color="#666" class="arrow-left" />
  129. <!-- <text>上一页</text> -->
  130. </view>
  131. <view class="page-numbers">
  132. <view v-for="page in visiblePages" :key="page" class="page-number"
  133. :class="{ active: pagination.current === page }" @click="handlePageChange(page)">
  134. {{ page }}
  135. </view>
  136. </view>
  137. <view class="page-item next" :class="{ disabled: pagination.current === pagination.pages }"
  138. @click="handlePageChange('next')">
  139. <!-- <text>下一页</text> -->
  140. <uni-icons type="arrowright" size="16" color="#666" />
  141. </view>
  142. </view>
  143. </view>
  144. <!-- 移动端详情弹窗 -->
  145. <!-- <cwg-detail-popup v-model:visible="detailVisible" title="详情" :items="detailItems" /> -->
  146. <cwg-detail-popup v-model:visible="detailVisible" title="详情" :row="detailRow" :columns="detailColumns">
  147. <template v-for="col in detailColumns" :key="col.prop" #[`cell-${col.prop}`]="{ row, column }">
  148. <slot v-if="col.slot" :name="col.slot" :row="row" :column="column" :index="0" />
  149. </template>
  150. </cwg-detail-popup>
  151. </view>
  152. </template>
  153. <script setup>
  154. import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
  155. import { getNoteText } from '@/utils/noteHelper';
  156. import useUserStore from "@/stores/use-user-store";
  157. import { useI18n } from "vue-i18n";
  158. const userStore = useUserStore();
  159. const { locale } = useI18n();
  160. const props = defineProps({
  161. /**
  162. * 表格列配置(columns 数组中每一项是一个列配置对象)
  163. * - prop: 字段名,对应 row[prop],用于取值/排序/详情展示
  164. * - label: 表头显示文本(也会作为详情弹窗的 label)
  165. * - align: 对齐方式('left' | 'center' | 'right')
  166. * - width: 列宽(设置后该列固定宽度;未设置则自适应
  167. * - slot: 自定义渲染插槽名(<template #xxx="{ row, column, index }">),优先级最高
  168. * - formatter: ({ value, row }) => string | number,自定义格式化显示值(无 slot 时生效)
  169. * - sortable: 是否可排序(点击表头切换 asc/desc)
  170. * - headerStyle: 表头样式(对象),会合并到表头 style
  171. * - cellStyle: 单元格样式(对象或函数({ row, column }) => style)
  172. * - cellClass: 单元格 class(string 或函数({ row, column }) => string | string[])
  173. * - isTabel: false 时不在表格中显示该列,但仍会在“详情弹窗”中显示
  174. * - type: 内置渲染类型
  175. * - 'tag': 使用 uni-tag 渲染,搭配 tagMap/tagTypeMap
  176. * - 'file': 使用 cwg-file 渲染
  177. * - 'more': 展示“更多”图标(用于移动端点击查看详情等)
  178. * - 'date': 日期格式化(搭配 dateFormat)
  179. * - 'action': 操作按钮
  180. * - tagMap: 标签映射对象
  181. * - tagTypeMap: 标签类型映射对象
  182. * - dateFormat: 日期格式
  183. * */
  184. columns: { type: Array, required: true, default: () => [] },
  185. // 移动端配置
  186. mobilePrimaryCount: { type: Number, default: 3 },
  187. // 参数如columns
  188. mobilePrimaryFields: { type: Array, default: () => [] },
  189. // API 请求函数
  190. api: { type: Function, required: true },
  191. // 查询参数
  192. queryParams: { type: Object, default: () => ({}) },
  193. // 是否立即加载
  194. immediate: { type: Boolean, default: true },
  195. // 选择类型:'selection' | null
  196. selectionType: { type: String, default: null },
  197. // 是否显示每页条数选择
  198. showPageSize: { type: Boolean, default: true },
  199. // 是否显示分页
  200. showPagination: { type: Boolean, default: true },
  201. isViewDetail: { type: Boolean, default: true },
  202. // 每页条数选项
  203. pageSizes: { type: Array, default: () => [2, 4, 6, 8, 10, 20, 30, 50, 100] },
  204. // 默认每页条数
  205. defaultPageSize: { type: Number, default: 10 },
  206. // 表头样式自定义
  207. headerBackground: { type: String, default: '#fff' },
  208. headerColor: { type: String, default: 'var(--color-slate-800)' },
  209. headerFontSize: { type: [String, Number], default: '14rpx' },
  210. headerFontWeight: { type: [String, Number], default: 600 },
  211. headerHeight: { type: [String, Number], default: '32rpx' },
  212. headerClass: { type: [String, Array], default: '' },
  213. headerStyle: { type: Object, default: () => ({}) },
  214. stickyHeader: { type: Boolean, default: true },
  215. stickyOffset: { type: [String, Number], default: '0' },
  216. isPages: { type: Boolean, default: false },
  217. // 是否显示总计行
  218. showSummary: { type: Boolean, default: false },
  219. // 自定义总计数据,若不传则尝试使用 api 响应中的 res.sum
  220. summaryData: { type: Object, default: () => null },
  221. // 自定义的合计计算方法,如果配置了,则使用该方法计算总计数据
  222. summaryMethod: { type: Function, default: null },
  223. // 总计行第一列的默认文本
  224. summaryText: { type: String, default: '总计' },
  225. })
  226. const emit = defineEmits([
  227. 'selection-change',
  228. 'action-click',
  229. 'page-change',
  230. 'load-success',
  231. 'load-error',
  232. 'sort-change',
  233. 'go-pages'
  234. ])
  235. // ========== 响应式状态 ==========
  236. const tableData = ref([])
  237. const selectedItems = ref([])
  238. const detailVisible = ref(false)
  239. const detailItems = ref([])
  240. // 替换原来的 detailItems 相关定义
  241. const detailRow = ref(null)
  242. const detailColumns = ref([])
  243. const pagination = ref({
  244. current: 1,
  245. pageSize: props.defaultPageSize,
  246. total: 0,
  247. pages: 0
  248. })
  249. const loading = ref(false)
  250. const expandedRows = ref({})
  251. const internalSummaryData = ref(null)
  252. const currentSummaryData = computed(() => {
  253. if (props.summaryData && Object.keys(props.summaryData).length > 0) return props.summaryData
  254. return internalSummaryData.value
  255. })
  256. const computedSummaryRow = computed(() => {
  257. if (props.showSummary && props.summaryMethod && typeof props.summaryMethod === 'function') {
  258. const result = props.summaryMethod({
  259. columns: displayColumns.value,
  260. data: tableData.value,
  261. summaryData: currentSummaryData.value
  262. });
  263. return Array.isArray(result) ? result : [];
  264. }
  265. return [];
  266. });
  267. // 移动端检测
  268. const isMobile = ref(false)
  269. // 排序状态
  270. const sortState = ref({ prop: '', order: '' }) // order: 'asc' | 'desc' | ''
  271. // action 列的状态
  272. const actionExpanded = ref({})
  273. const getVisibleActions = (menuList, row) => {
  274. if (!menuList) return []
  275. return menuList.filter(item => {
  276. if (typeof item.show === 'function') {
  277. return item.show(row) !== false
  278. }
  279. return item.show !== false
  280. })
  281. }
  282. const toggleAction = (rowIndex, prop) => {
  283. const key = `${rowIndex}-${prop}`
  284. actionExpanded.value[key] = !actionExpanded.value[key]
  285. }
  286. // ========== 计算属性 ==========
  287. // 显示的列(根据设备类型)
  288. const displayColumns = computed(() => {
  289. const filterForTable = (cols) => (cols || []).filter((c) => c && c.isTabel !== false)
  290. const normalizeColumns = (cols) => {
  291. if (!Array.isArray(cols)) return []
  292. if (cols.length === 0) return []
  293. const first = cols[0]
  294. if (typeof first === 'string') {
  295. return cols
  296. .map((prop) => props.columns.find((c) => c && c.prop === prop))
  297. .filter(Boolean)
  298. }
  299. return cols
  300. }
  301. if (!isMobile.value) return filterForTable(normalizeColumns(props.columns))
  302. if (props.mobilePrimaryFields && props.mobilePrimaryFields.length) {
  303. return filterForTable(normalizeColumns(props.mobilePrimaryFields))
  304. }
  305. return filterForTable(normalizeColumns(props.columns.slice(0, props.mobilePrimaryCount)))
  306. })
  307. // 列跨度(用于展开行)
  308. const columnSpan = computed(() => {
  309. let span = displayColumns.value.length
  310. if (props.showOperation) span += 1
  311. return span
  312. })
  313. // 每页条数索引
  314. const pageSizeIndex = computed(() => {
  315. return props.pageSizes.indexOf(pagination.value.pageSize)
  316. })
  317. // 可见页码
  318. const visiblePages = computed(() => {
  319. const maxVisible = 5
  320. const half = Math.floor(maxVisible / 2)
  321. let start = Math.max(1, pagination.value.current - half)
  322. let end = Math.min(pagination.value.pages, start + maxVisible - 1)
  323. if (end - start + 1 < maxVisible) {
  324. start = Math.max(1, end - maxVisible + 1)
  325. }
  326. return Array.from({ length: end - start + 1 }, (_, i) => start + i)
  327. })
  328. // ========== 工具函数 ==========
  329. // 获取表头样式
  330. const getHeaderStyle = (column) => {
  331. const baseStyle = {
  332. backgroundColor: props.headerBackground,
  333. color: props.headerColor,
  334. fontSize: typeof props.headerFontSize === 'number' ? props.headerFontSize + 'rpx' : props.headerFontSize,
  335. fontWeight: props.headerFontWeight,
  336. height: typeof props.headerHeight === 'number' ? props.headerHeight + 'rpx' : props.headerHeight,
  337. lineHeight: typeof props.headerHeight === 'number' ? props.headerHeight + 'rpx' : props.headerHeight,
  338. ...props.headerStyle
  339. }
  340. if (props.stickyHeader) {
  341. baseStyle.position = 'sticky'
  342. baseStyle.top = props.stickyOffset
  343. baseStyle.zIndex = 100
  344. }
  345. if (column.width) {
  346. const w = typeof column.width === 'number' ? column.width + 'px' : column.width
  347. baseStyle.width = w
  348. baseStyle.minWidth = w
  349. baseStyle.maxWidth = w
  350. }
  351. if (column.headerStyle) {
  352. Object.assign(baseStyle, column.headerStyle)
  353. }
  354. return baseStyle
  355. }
  356. // 获取单元格样式
  357. const getCellStyle = (column, row) => {
  358. const style = {}
  359. if (column.width) {
  360. const w = typeof column.width === 'number' ? column.width + 'px' : column.width
  361. style.width = w
  362. style.minWidth = w
  363. style.maxWidth = w
  364. style.wordBreak = 'break-all'
  365. // 如果是自定义插槽,允许内容换行或由内部元素自己控制溢出,不强制隐藏
  366. if (column.slot) {
  367. style.whiteSpace = 'normal'
  368. style.overflow = 'visible'
  369. style.textOverflow = 'clip'
  370. } else {
  371. style.whiteSpace = 'nowrap'
  372. style.overflow = 'hidden'
  373. style.textOverflow = 'ellipsis'
  374. }
  375. } else {
  376. // 如果没有定宽,保证默认情况下单元格内容不会被直接 hidden 切掉下拉弹窗
  377. if (column.slot) {
  378. style.overflow = 'visible'
  379. }
  380. }
  381. if (column.cellStyle) {
  382. if (typeof column.cellStyle === 'function') {
  383. Object.assign(style, column.cellStyle({ row, column }))
  384. } else {
  385. Object.assign(style, column.cellStyle)
  386. }
  387. }
  388. return style
  389. }
  390. // 获取单元格类名
  391. const getCellClass = (column, row) => {
  392. const classes = []
  393. if (column.cellClass) {
  394. if (typeof column.cellClass === 'function') {
  395. const result = column.cellClass({ row, column })
  396. if (result) {
  397. if (Array.isArray(result)) {
  398. classes.push(...result)
  399. } else {
  400. classes.push(result)
  401. }
  402. }
  403. } else {
  404. classes.push(column.cellClass)
  405. }
  406. }
  407. return classes.join(' ')
  408. }
  409. // 格式化单元格值
  410. const formatCellValue = (value, column, row) => {
  411. if (column.formatter) {
  412. return column.formatter({ value, row })
  413. }
  414. if (column.type === 'date' && value) {
  415. return formatDate(value, column.dateFormat || 'YYYY-MM-DD HH:mm:ss')
  416. }
  417. if (column.type === 'tag' && value) {
  418. return formatTagText(value, row)
  419. }
  420. if (value === null || value === undefined) {
  421. return '-'
  422. }
  423. return value
  424. }
  425. // 格式化标签文本
  426. const formatTagText = (value, column) => {
  427. if (column.tagMap && column.tagMap[value]) {
  428. return column.tagMap[value]
  429. }
  430. return value || '-'
  431. }
  432. // 格式化标签类型
  433. const formatTagType = (value, column) => {
  434. if (column.tagTypeMap && column.tagTypeMap[value]) {
  435. return column.tagTypeMap[value]
  436. }
  437. return 'default'
  438. }
  439. // 格式化日期
  440. const formatDate = (date, format) => {
  441. if (!date) return '-'
  442. const d = new Date(date)
  443. const year = d.getFullYear()
  444. const month = String(d.getMonth() + 1).padStart(2, '0')
  445. const day = String(d.getDate()).padStart(2, '0')
  446. const hour = String(d.getHours()).padStart(2, '0')
  447. const minute = String(d.getMinutes()).padStart(2, '0')
  448. const second = String(d.getSeconds()).padStart(2, '0')
  449. return format
  450. .replace('YYYY', year)
  451. .replace('MM', month)
  452. .replace('DD', day)
  453. .replace('HH', hour)
  454. .replace('mm', minute)
  455. .replace('ss', second)
  456. }
  457. // 排序图标
  458. const getSortIcon = (column) => {
  459. if (sortState.value.prop !== column.prop) return 'arrow-up'
  460. return sortState.value.order === 'asc' ? 'arrow-up' : 'arrow-down'
  461. }
  462. // 处理排序
  463. const handleSort = (column) => {
  464. if (!column.sortable) return
  465. let newOrder = ''
  466. if (sortState.value.prop === column.prop) {
  467. if (sortState.value.order === '') newOrder = 'asc'
  468. else if (sortState.value.order === 'asc') newOrder = 'desc'
  469. else newOrder = ''
  470. } else {
  471. newOrder = 'asc'
  472. }
  473. sortState.value = { prop: newOrder ? column.prop : '', order: newOrder }
  474. emit('sort-change', { prop: sortState.value.prop, order: sortState.value.order })
  475. refreshTable()
  476. }
  477. // 展开行切换
  478. const toggleRowExpand = (rowIndex) => {
  479. const key = rowIndex
  480. if (expandedRows.value[key]) {
  481. expandedRows.value[key] = false
  482. } else {
  483. expandedRows.value = {}
  484. expandedRows.value[key] = true
  485. }
  486. emit('expand-change', { rowIndex, expanded: expandedRows.value[key] })
  487. }
  488. // 打开详情弹窗(移动端使用)
  489. // 修改 openRowDetail
  490. const openRowDetail = (row) => {
  491. if (props.isPages) {
  492. emit('go-pages', row)
  493. } else if (!isMobile.value){
  494. // 只有移动端才打开详情弹窗
  495. return
  496. }else {
  497. // 保存当前行和需要显示的列(有 prop 且有 label) pc 详情不展示操作按钮
  498. detailRow.value = { ...row, note: getNoteText(row, locale.value, userStore) }
  499. detailColumns.value = !isMobile.value ? props.columns.filter(col => col && col.prop && col.label && col.type !== 'action') : props.columns.filter(col => col && col.prop && col.label)
  500. detailVisible.value = true
  501. }
  502. }
  503. const setDetailVisible = (visible) => {
  504. detailVisible.value = visible
  505. }
  506. // ========== 数据加载 ==========
  507. const loadData = async () => {
  508. tableData.value = []
  509. if (loading.value) return
  510. loading.value = true
  511. try {
  512. const applyPaginationFromRes = (res) => {
  513. const page = res && res.page
  514. if (!page) return false
  515. if (typeof page.current === 'number') pagination.value.current = page.current
  516. if (typeof page.row === 'number') pagination.value.pageSize = page.row
  517. if (typeof page.rowTotal === 'number') pagination.value.total = page.rowTotal
  518. if (typeof page.pageTotal === 'number') pagination.value.pages = page.pageTotal
  519. else if (typeof pagination.value.total === 'number' && typeof pagination.value.pageSize === 'number') {
  520. pagination.value.pages = Math.ceil(pagination.value.total / pagination.value.pageSize)
  521. }
  522. return true
  523. }
  524. // 👇 修复后:使用解构获取最新的 queryParams,杜绝延迟
  525. const query = { ...props.queryParams };
  526. let startDate = "";
  527. let endDate = "";
  528. // 处理日期范围(用解构后的 query,绝对最新)
  529. if (!query.date || query.date.length === 0) {
  530. startDate = "";
  531. endDate = "";
  532. } else {
  533. startDate = query.date[0] || "";
  534. endDate = query.date[1] || "";
  535. }
  536. // 组装请求参数
  537. const params = {
  538. page: {
  539. current: pagination.value.current,
  540. row: pagination.value.pageSize
  541. },
  542. ...query, // 用解构后的最新 query
  543. startDate,
  544. endDate
  545. };
  546. // 添加排序参数
  547. if (sortState.value.prop && sortState.value.order) {
  548. params.sort = { field: sortState.value.prop, order: sortState.value.order }
  549. }
  550. const res = await props.api(params)
  551. if (res.code === 200 || res.code === 0 || res.code === 10000) {
  552. if (res.sum) {
  553. internalSummaryData.value = res.sum
  554. } else {
  555. internalSummaryData.value = null
  556. }
  557. const data = res.data || res
  558. const hasPage = applyPaginationFromRes(res)
  559. if (Array.isArray(data)) {
  560. tableData.value = data
  561. if (!hasPage) {
  562. pagination.value.total = data.length
  563. pagination.value.pages = 1
  564. }
  565. } else if (data.list || data.records) {
  566. tableData.value = data.list || data.records
  567. if (!hasPage) {
  568. pagination.value.total = data.total || data.list?.length || 0
  569. pagination.value.pages = data.pages || Math.ceil(pagination.value.total / pagination.value.pageSize)
  570. }
  571. } else {
  572. tableData.value = []
  573. }
  574. emit('load-success', res)
  575. } else {
  576. throw new Error(res.message || '加载失败')
  577. }
  578. } catch (error) {
  579. console.error('表格数据加载失败:', error)
  580. uni.showToast({
  581. title: error.message || '加载失败',
  582. icon: 'none'
  583. })
  584. emit('load-error', error)
  585. } finally {
  586. loading.value = false
  587. pageLoading.value = false
  588. }
  589. }
  590. // 刷新表格
  591. const refreshTable = () => {
  592. pagination.value.current = 1
  593. loadData()
  594. }
  595. const reload = () => {
  596. loadData()
  597. }
  598. const pageLoading = ref(false)
  599. // 分页变化
  600. const handlePageChange = (page) => {
  601. if (pageLoading.value) return
  602. pageLoading.value = true
  603. if (page === 'prev') {
  604. if (pagination.value.current > 1) pagination.value.current--
  605. else return
  606. } else if (page === 'next') {
  607. if (pagination.value.current < pagination.value.pages) pagination.value.current++
  608. else return
  609. } else {
  610. pagination.value.current = page
  611. }
  612. loadData()
  613. emit('page-change', pagination.value)
  614. }
  615. // 每页条数变化
  616. const handlePageSizeChange = (e) => {
  617. const size = props.pageSizes[e.detail.value]
  618. pagination.value.pageSize = size
  619. pagination.value.current = 1
  620. loadData()
  621. }
  622. // 选择变化
  623. const handleSelectionChange = (e) => {
  624. selectedItems.value = e.detail.value
  625. emit('selection-change', selectedItems.value)
  626. }
  627. // 获取选中项
  628. const getSelectedItems = () => selectedItems.value
  629. const clearSelection = () => { selectedItems.value = [] }
  630. // ========== 移动端检测 ==========
  631. const checkIsMobile = () => {
  632. // 适配 uni-app 环境
  633. // #ifdef H5
  634. const width = window.innerWidth
  635. isMobile.value = width < 991
  636. // #endif
  637. // #ifndef H5
  638. const systemInfo = uni.getSystemInfoSync()
  639. isMobile.value = systemInfo.windowWidth < 991
  640. // #endif
  641. }
  642. // 监听窗口大小变化(仅 H5)
  643. // #ifdef H5
  644. const handleResize = () => {
  645. checkIsMobile()
  646. }
  647. // #endif
  648. // ========== 监听参数变化 ==========
  649. watch(() => props.queryParams, () => {
  650. nextTick(() => {
  651. // refreshTable()
  652. })
  653. }, { deep: true })
  654. watch(() => props.api, () => {
  655. nextTick(() => {
  656. refreshTable()
  657. })
  658. }, { deep: true })
  659. // ========== 生命周期 ==========
  660. onMounted(() => {
  661. checkIsMobile()
  662. // #ifdef H5
  663. window.addEventListener('resize', handleResize)
  664. // #endif
  665. if (props.immediate) {
  666. loadData()
  667. }
  668. })
  669. onUnmounted(() => {
  670. // #ifdef H5
  671. window.removeEventListener('resize', handleResize)
  672. // #endif
  673. })
  674. // 暴露方法
  675. defineExpose({
  676. refreshTable,
  677. reload,
  678. getSelectedItems,
  679. clearSelection,
  680. loadData,
  681. tableData,
  682. toggleRowExpand,
  683. pagination,
  684. setDetailVisible
  685. })
  686. </script>
  687. <style scoped lang="scss">
  688. @import "@/uni.scss";
  689. .table-container {
  690. width: 100%;
  691. // overflow-x: auto;
  692. // -webkit-overflow-scrolling: touch;
  693. margin-top: px2rpx(20);
  694. max-height: calc(100vh - 209px);
  695. color: var(--color-slate-800);
  696. .table-loading-mask {
  697. width: 100%;
  698. height: 100%;
  699. // margin: 0 auto;
  700. display: flex;
  701. align-items: center;
  702. justify-content: center;
  703. }
  704. :deep(.uni-table-scroll) {
  705. width: 100%;
  706. max-height: calc(100vh - 375px);
  707. //min-height: 300px;
  708. overflow-y: auto;
  709. overflow-x: auto;
  710. /* 强制显示滚动条并美化 */
  711. &::-webkit-scrollbar {
  712. width: 8px;
  713. height: 8px;
  714. display: block;
  715. /* 强制在某些webkit浏览器中显示 */
  716. background-color: transparent;
  717. }
  718. &::-webkit-scrollbar-track {
  719. background-color: #f5f5f5;
  720. border-radius: 4px;
  721. }
  722. &::-webkit-scrollbar-thumb {
  723. background-color: #c0c4cc;
  724. border-radius: 4px;
  725. &:hover {
  726. background-color: #909399;
  727. }
  728. }
  729. }
  730. :deep(.uni-table) {
  731. border-radius: 8px;
  732. box-shadow: 0 1px 4px rgba(0, 0, 0, 0.02);
  733. .uni-table-th {
  734. position: sticky;
  735. top: 0;
  736. z-index: 100;
  737. transition: all 0.3s;
  738. background-color: #fafafa !important;
  739. border-bottom: 1px solid #ebeef5 !important;
  740. color: #606266;
  741. .header-content {
  742. display: flex;
  743. align-items: center;
  744. justify-content: center;
  745. gap: 4px;
  746. .sort-icon {
  747. display: inline-flex;
  748. cursor: pointer;
  749. }
  750. }
  751. &.sortable {
  752. cursor: pointer;
  753. &:hover .sort-icon .uni-icons {
  754. color: var(--color-primary) !important;
  755. }
  756. }
  757. &::after {
  758. display: none;
  759. }
  760. }
  761. .uni-table-tr {
  762. transition: background-color 0.2s ease;
  763. border-bottom: 1px solid #ebeef5 !important;
  764. &:hover {
  765. background-color: #f5f7fa !important;
  766. }
  767. &:last-child {
  768. border-bottom: none !important;
  769. }
  770. }
  771. .summary-row {
  772. background-color: #fafafa;
  773. font-weight: 600;
  774. .uni-table-td {
  775. border-top: 1px solid #ebeef5 !important;
  776. position: sticky;
  777. bottom: 0;
  778. z-index: 99;
  779. background-color: #fafafa;
  780. }
  781. }
  782. .uni-table-td {
  783. padding: px2rpx(16) px2rpx(5);
  784. color: #303133;
  785. box-sizing: border-box;
  786. vertical-align: middle;
  787. font-size: 14px;
  788. white-space: nowrap;
  789. }
  790. .uni-table-th {
  791. padding: px2rpx(6) px2rpx(5);
  792. box-sizing: border-box;
  793. vertical-align: middle;
  794. font-size: 14px;
  795. white-space: nowrap;
  796. word-break: keep-all;
  797. }
  798. .action-wrapper {
  799. max-width: 180px;
  800. white-space: normal;
  801. }
  802. .action-list {
  803. display: flex;
  804. flex-wrap: wrap;
  805. gap: 6px 5px;
  806. align-items: center;
  807. }
  808. .action-btn {
  809. color: var(--color-primary);
  810. text-decoration: underline;
  811. cursor: pointer;
  812. font-size: px2rpx(12);
  813. white-space: nowrap;
  814. }
  815. .action-toggle-btn {
  816. color: #909399;
  817. cursor: pointer;
  818. font-size: px2rpx(12);
  819. white-space: nowrap;
  820. }
  821. .expand-cell {
  822. padding: 0 !important;
  823. }
  824. }
  825. }
  826. .crm-chevron-down {
  827. transform: rotate(-90deg);
  828. cursor: pointer;
  829. }
  830. .mobile-table {
  831. :deep(.uni-table) {
  832. min-width: 0 !important;
  833. }
  834. }
  835. .detail-btn-mobile {
  836. background-color: #f0f0f0;
  837. color: #333;
  838. }
  839. /* 分页样式 */
  840. .pagination-container {
  841. margin: px2rpx(20) 0;
  842. display: flex;
  843. align-items: center;
  844. justify-content: flex-end;
  845. gap: px2rpx(20);
  846. position: relative;
  847. z-index: 10;
  848. background-color: transparent;
  849. .pagination {
  850. display: flex;
  851. align-items: center;
  852. //padding: px2rpx(10);
  853. }
  854. .page-item {
  855. display: flex;
  856. align-items: center;
  857. padding: 0 px2rpx(12);
  858. height: px2rpx(30);
  859. background-color: var(--color-white);
  860. border: 1px solid #dcdfe6;
  861. border-radius: px2rpx(8);
  862. font-size: px2rpx(16);
  863. color: #606266;
  864. cursor: pointer;
  865. transition: all 0.3s;
  866. margin: 0 px2rpx(6);
  867. }
  868. .page-item.prev {
  869. margin-right: px2rpx(10);
  870. }
  871. .page-item.next {
  872. margin-left: px2rpx(10);
  873. }
  874. .page-item:not(.disabled):hover {
  875. color: #007aff;
  876. border-color: #007aff;
  877. }
  878. .page-item.disabled {
  879. opacity: 0.5;
  880. cursor: not-allowed;
  881. pointer-events: none;
  882. }
  883. .page-numbers {
  884. display: flex;
  885. gap: px2rpx(8);
  886. }
  887. .arrow-left {
  888. transform: rotate(180deg);
  889. }
  890. .page-number {
  891. display: flex;
  892. align-items: center;
  893. justify-content: center;
  894. min-width: px2rpx(40);
  895. height: px2rpx(30);
  896. padding: 0 px2rpx(4);
  897. background-color: var(--color-white);
  898. border-radius: px2rpx(8);
  899. font-size: px2rpx(16);
  900. color: #606266;
  901. cursor: pointer;
  902. transition: all 0.3s;
  903. }
  904. .page-number:hover {
  905. color: #007aff;
  906. border-color: #007aff;
  907. }
  908. .page-number.active {
  909. background-color: #cf1322;
  910. border-color: #007aff;
  911. color: #fff;
  912. }
  913. .pagination-info {
  914. display: flex;
  915. align-items: center;
  916. gap: px2rpx(30);
  917. font-size: px2rpx(16);
  918. color: #909399;
  919. }
  920. .page-size-select {
  921. display: flex;
  922. align-items: center;
  923. gap: px2rpx(10);
  924. }
  925. .page-size-value {
  926. padding: px2rpx(6) px2rpx(20);
  927. border: 1px solid #dcdfe6;
  928. border-radius: px2rpx(8);
  929. color: #606266;
  930. }
  931. }
  932. @media screen and (max-width: 768px) {
  933. .pagination {
  934. flex-wrap: wrap;
  935. justify-content: center;
  936. }
  937. .page-item {
  938. padding: 0 px2rpx(16);
  939. }
  940. .page-number {
  941. min-width: px2rpx(60);
  942. }
  943. .pagination-info {
  944. flex-direction: column;
  945. gap: px2rpx(10);
  946. }
  947. }
  948. </style>