cwg-tabel.vue 38 KB

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