cwg-tabel.vue 39 KB

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