cwg-tabel.vue 35 KB

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