cwg-tabel.vue 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  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 = 4 // 显示的页码数量(包括第一页和最后一页)
  334. if (totalPages <= maxVisible) {
  335. return Array.from({ length: totalPages }, (_, i) => i + 1)
  336. }
  337. let pages = []
  338. if (currentPage <= 2) {
  339. // 当前页靠前:[1, 2, '...', 最后一页]
  340. pages = [1, 2, '...', totalPages]
  341. } else if (currentPage >= totalPages - 1) {
  342. // 当前页靠后:[1, '...', 倒数第二页, 最后一页]
  343. pages = [1, '...', totalPages - 1, totalPages]
  344. } else {
  345. // 当前页在中间:由于只显示4个,去掉后面的...直接紧凑展示:[1, '...', 当前页, 最后一页]
  346. // 或者:[1, 当前页, '...', 最后一页] 以确保当前页能点到
  347. pages = [1, '...', currentPage, totalPages]
  348. }
  349. return pages
  350. })
  351. // ========== 工具函数 ==========
  352. // 获取表头样式
  353. const getHeaderStyle = (column) => {
  354. const baseStyle = {
  355. backgroundColor: props.headerBackground,
  356. color: props.headerColor,
  357. fontSize: typeof props.headerFontSize === 'number' ? props.headerFontSize + 'rpx' : props.headerFontSize,
  358. fontWeight: props.headerFontWeight,
  359. height: typeof props.headerHeight === 'number' ? props.headerHeight + 'rpx' : props.headerHeight,
  360. lineHeight: typeof props.headerHeight === 'number' ? props.headerHeight + 'rpx' : props.headerHeight,
  361. ...props.headerStyle
  362. }
  363. if (props.stickyHeader) {
  364. baseStyle.position = 'sticky'
  365. baseStyle.top = props.stickyOffset
  366. baseStyle.zIndex = 100
  367. }
  368. if (column.width) {
  369. const w = typeof column.width === 'number' ? column.width + 'px' : column.width
  370. baseStyle.width = w
  371. baseStyle.minWidth = w
  372. baseStyle.maxWidth = w
  373. }
  374. if (column.headerStyle) {
  375. Object.assign(baseStyle, column.headerStyle)
  376. }
  377. return baseStyle
  378. }
  379. // 获取单元格样式
  380. const getCellStyle = (column, row) => {
  381. const style = {}
  382. if (column.width) {
  383. const w = typeof column.width === 'number' ? column.width + 'px' : column.width
  384. style.width = w
  385. style.minWidth = w
  386. style.maxWidth = w
  387. style.wordBreak = 'break-all'
  388. // 如果是自定义插槽,允许内容换行或由内部元素自己控制溢出,不强制隐藏
  389. if (column.slot) {
  390. style.whiteSpace = 'normal'
  391. style.overflow = 'visible'
  392. style.textOverflow = 'clip'
  393. } else {
  394. style.whiteSpace = 'nowrap'
  395. style.overflow = 'hidden'
  396. style.textOverflow = 'ellipsis'
  397. }
  398. } else {
  399. // 如果没有定宽,保证默认情况下单元格内容不会被直接 hidden 切掉下拉弹窗
  400. if (column.slot) {
  401. style.overflow = 'visible'
  402. }
  403. }
  404. if (column.cellStyle) {
  405. if (typeof column.cellStyle === 'function') {
  406. Object.assign(style, column.cellStyle({ row, column }))
  407. } else {
  408. Object.assign(style, column.cellStyle)
  409. }
  410. }
  411. return style
  412. }
  413. // 获取单元格类名
  414. const getCellClass = (column, row) => {
  415. const classes = []
  416. if (column.cellClass) {
  417. if (typeof column.cellClass === 'function') {
  418. const result = column.cellClass({ row, column })
  419. if (result) {
  420. if (Array.isArray(result)) {
  421. classes.push(...result)
  422. } else {
  423. classes.push(result)
  424. }
  425. }
  426. } else {
  427. classes.push(column.cellClass)
  428. }
  429. }
  430. // 跳转页面的时候加上鼠标小手
  431. if (props.isPages){
  432. classes.push('cursor-pointer')
  433. }
  434. return classes.join(' ')
  435. }
  436. // 格式化单元格值
  437. const formatCellValue = (value, column, row) => {
  438. if (column.formatter) {
  439. return column.formatter({ value, row })
  440. }
  441. if (column.type === 'date' && value) {
  442. return formatDate(value, column.dateFormat || 'YYYY-MM-DD HH:mm:ss')
  443. }
  444. if (column.type === 'tag' && value) {
  445. return formatTagText(value, row)
  446. }
  447. if (value === null || value === undefined) {
  448. return '-'
  449. }
  450. return value
  451. }
  452. // 格式化标签文本
  453. const formatTagText = (value, column) => {
  454. if (column.tagMap && column.tagMap[value]) {
  455. return column.tagMap[value]
  456. }
  457. return value || '-'
  458. }
  459. // 格式化标签类型
  460. const formatTagType = (value, column) => {
  461. if (column.tagTypeMap && column.tagTypeMap[value]) {
  462. return column.tagTypeMap[value]
  463. }
  464. return 'default'
  465. }
  466. // 格式化日期
  467. const formatDate = (date, format) => {
  468. if (!date) return '-'
  469. const d = new Date(date)
  470. const year = d.getFullYear()
  471. const month = String(d.getMonth() + 1).padStart(2, '0')
  472. const day = String(d.getDate()).padStart(2, '0')
  473. const hour = String(d.getHours()).padStart(2, '0')
  474. const minute = String(d.getMinutes()).padStart(2, '0')
  475. const second = String(d.getSeconds()).padStart(2, '0')
  476. return format
  477. .replace('YYYY', year)
  478. .replace('MM', month)
  479. .replace('DD', day)
  480. .replace('HH', hour)
  481. .replace('mm', minute)
  482. .replace('ss', second)
  483. }
  484. // 排序图标
  485. const getSortIcon = (column) => {
  486. if (sortState.value.prop !== column.prop) return 'arrow-up'
  487. return sortState.value.order === 'asc' ? 'arrow-up' : 'arrow-down'
  488. }
  489. // 处理排序
  490. const handleSort = (column) => {
  491. if (!column.sortable) return
  492. let newOrder = ''
  493. if (sortState.value.prop === column.prop) {
  494. if (sortState.value.order === '') newOrder = 'asc'
  495. else if (sortState.value.order === 'asc') newOrder = 'desc'
  496. else newOrder = ''
  497. } else {
  498. newOrder = 'asc'
  499. }
  500. sortState.value = { prop: newOrder ? column.prop : '', order: newOrder }
  501. emit('sort-change', { prop: sortState.value.prop, order: sortState.value.order })
  502. // refreshTable()
  503. }
  504. // 展开行切换
  505. const toggleRowExpand = (rowIndex) => {
  506. const key = rowIndex
  507. if (expandedRows.value[key]) {
  508. expandedRows.value[key] = false
  509. } else {
  510. expandedRows.value = {}
  511. expandedRows.value[key] = true
  512. }
  513. emit('expand-change', { rowIndex, expanded: expandedRows.value[key] })
  514. }
  515. // 打开详情弹窗(移动端使用)
  516. // 修改 openRowDetail
  517. const openRowDetail = (row) => {
  518. if (props.isPages) {
  519. emit('go-pages', row)
  520. } else {
  521. if (props.pagesToDetail) {
  522. emit('go-pages', row)
  523. } else if (isMobile.value) {
  524. // 保存当前行和需要显示的列(有 prop 且有 label) pc 详情不展示操作按钮
  525. detailRow.value = { ...row, note: getNoteText(row, locale.value, userStore) }
  526. 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)
  527. detailVisible.value = true
  528. }
  529. }
  530. }
  531. const setDetailVisible = (visible) => {
  532. detailVisible.value = visible
  533. }
  534. // ========== 数据加载 ==========
  535. const loadData = async () => {
  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. pagination.value.current = 1
  628. loadData()
  629. }
  630. const reload = () => {
  631. loadData()
  632. }
  633. const pageLoading = ref(false)
  634. // 分页变化
  635. const handlePageChange = (page) => {
  636. if (pageLoading.value) return
  637. pageLoading.value = true
  638. if (page === 'prev') {
  639. if (pagination.value.current > 1) pagination.value.current--
  640. else return
  641. } else if (page === 'next') {
  642. if (pagination.value.current < pagination.value.pages) pagination.value.current++
  643. else return
  644. } else {
  645. pagination.value.current = page
  646. }
  647. loadData()
  648. emit('page-change', pagination.value)
  649. }
  650. // 每页条数变化
  651. const handlePageSizeChange = (e) => {
  652. const size = props.pageSizes[e.detail.value]
  653. pagination.value.pageSize = size
  654. pagination.value.current = 1
  655. loadData()
  656. }
  657. // 选择变化
  658. const handleSelectionChange = (e) => {
  659. selectedItems.value = e.detail.value
  660. emit('selection-change', selectedItems.value)
  661. }
  662. // 获取选中项
  663. const getSelectedItems = () => selectedItems.value
  664. const clearSelection = () => { selectedItems.value = [] }
  665. // ========== 移动端检测 ==========
  666. const checkIsMobile = () => {
  667. // 适配 uni-app 环境
  668. // #ifdef H5
  669. const width = window.innerWidth
  670. isMobile.value = width < 991
  671. // #endif
  672. // #ifndef H5
  673. const systemInfo = uni.getSystemInfoSync()
  674. isMobile.value = systemInfo.windowWidth < 991
  675. // #endif
  676. }
  677. // 监听窗口大小变化(仅 H5)
  678. // #ifdef H5
  679. const handleResize = () => {
  680. checkIsMobile()
  681. }
  682. // #endif
  683. // ========== 监听参数变化 ==========
  684. watch(() => props.data, (newData) => {
  685. if (newData) {
  686. tableData.value = newData
  687. }
  688. }, { deep: true, immediate: true })
  689. watch(() => props.summaryData, (newSum) => {
  690. if (props.data && newSum) {
  691. internalSummaryData.value = newSum
  692. }
  693. }, { deep: true, immediate: true })
  694. watch(() => props.queryParams, () => {
  695. nextTick(() => {
  696. // refreshTable()
  697. })
  698. }, { deep: true })
  699. watch(() => props.api, () => {
  700. nextTick(() => {
  701. refreshTable()
  702. })
  703. }, { deep: true })
  704. // ========== 生命周期 ==========
  705. onMounted(() => {
  706. checkIsMobile()
  707. // #ifdef H5
  708. window.addEventListener('resize', handleResize)
  709. // #endif
  710. if (props.immediate) {
  711. loadData()
  712. }
  713. })
  714. onUnmounted(() => {
  715. // #ifdef H5
  716. window.removeEventListener('resize', handleResize)
  717. // #endif
  718. })
  719. // 暴露方法
  720. defineExpose({
  721. refreshTable,
  722. reload,
  723. getSelectedItems,
  724. clearSelection,
  725. loadData,
  726. tableData,
  727. toggleRowExpand,
  728. pagination,
  729. setDetailVisible
  730. })
  731. </script>
  732. <style scoped lang="scss">
  733. @import "@/uni.scss";
  734. .table-container {
  735. width: 100%;
  736. position: relative;
  737. overflow-x: auto;
  738. -webkit-overflow-scrolling: touch;
  739. margin-top: px2rpx(20);
  740. max-height: calc(100vh - 209px);
  741. color: var(--color-slate-800);
  742. box-shadow: none;
  743. .table-body-area {
  744. display: flex;
  745. flex-direction: column;
  746. min-height: px2rpx(360);
  747. &.is-empty,
  748. &.is-loading {
  749. :deep(.uni-table-scroll) {
  750. flex-shrink: 0;
  751. overflow: visible;
  752. }
  753. }
  754. }
  755. .table-empty-state {
  756. flex: 1;
  757. display: flex;
  758. align-items: center;
  759. justify-content: center;
  760. min-height: px2rpx(280);
  761. padding: px2rpx(24) px2rpx(20) px2rpx(40);
  762. box-sizing: border-box;
  763. }
  764. .action-wrapper {
  765. display: flex;
  766. justify-content: center;
  767. align-items: center;
  768. .action-trigger {
  769. display: flex;
  770. justify-content: center;
  771. align-items: center;
  772. cursor: pointer;
  773. padding: px2rpx(4);
  774. border-radius: px2rpx(4);
  775. transition: background-color 0.2s;
  776. &:hover {
  777. background-color: rgba(0, 0, 0, 0.05);
  778. }
  779. }
  780. }
  781. .table-loading-mask {
  782. width: 100%;
  783. height: 100%;
  784. // margin: 0 auto;
  785. display: flex;
  786. align-items: center;
  787. justify-content: center;
  788. }
  789. :deep(.uni-table-scroll) {
  790. width: 100%;
  791. max-height: calc(100vh - 375px);
  792. min-height: px2rpx(300);
  793. overflow-y: auto;
  794. overflow-x: auto;
  795. /* 强制显示滚动条并美化 */
  796. &::-webkit-scrollbar {
  797. width: 4px !important;
  798. height: 4px !important;
  799. display: block !important;
  800. /* 强制在某些webkit浏览器中显示 */
  801. background-color:yellow !important;
  802. }
  803. &::-webkit-scrollbar-track {
  804. background-color: #faf3f3;
  805. border-radius: 4px;
  806. }
  807. &::-webkit-scrollbar-thumb {
  808. background-color:#6a6a6a;
  809. border-radius: 4px;
  810. &:hover {
  811. background-color: #6a6a6a;
  812. }
  813. }
  814. }
  815. :deep(.uni-table) {
  816. border-radius: 8px;
  817. //box-shadow: 0 1px 4px rgba(0, 0, 0, 0.02);
  818. height: 100%;
  819. .uni-table-th {
  820. position: sticky;
  821. top: 0;
  822. z-index: 100;
  823. transition: all 0.3s;
  824. background-color: var(--table-th-color) !important;
  825. border-bottom: 1px solid var(--bs-light-bg-subtle) !important;
  826. color: #000 !important;
  827. padding-left: px2rpx(10);
  828. .header-content {
  829. display: flex;
  830. align-items: center;
  831. justify-content: center;
  832. gap: 4px;
  833. .sort-icon {
  834. display: inline-flex;
  835. cursor: pointer;
  836. }
  837. }
  838. &.sortable {
  839. cursor: pointer;
  840. &:hover .sort-icon .uni-icons {
  841. color: var(--color-primary) !important;
  842. }
  843. }
  844. &::after {
  845. display: none;
  846. }
  847. }
  848. .uni-table-tr {
  849. transition: background-color 0.2s ease;
  850. border-bottom: 1px solid var(--bs-light-bg-subtle) !important;
  851. color: var(--bs-emphasis-color) !important;
  852. // 奇数行背景颜色
  853. &:nth-child(odd) {
  854. // 暂时用一样的颜色
  855. background-color: var(--bs-light-bg-subtle);
  856. //background-color: var(--bs-body-bg);
  857. }
  858. // 偶数行背景颜色
  859. &:nth-child(even) {
  860. background-color: var(--bs-body-bg);
  861. }
  862. &:hover {
  863. background-color: var(--bs-light-bg-subtle) !important;
  864. }
  865. &:last-child {
  866. border-bottom: none !important;
  867. }
  868. }
  869. .summary-row {
  870. background-color: var(--table-th-color);
  871. font-weight: 600;
  872. .uni-table-td {
  873. border-top: 1px solid var(--table-th-color) !important;
  874. position: sticky;
  875. bottom: 0;
  876. z-index: 99;
  877. background-color: var(--table-th-color);
  878. }
  879. }
  880. .uni-table-td {
  881. padding: px2rpx(16) px2rpx(15);
  882. color: var(--bs-emphasis-color) !important;
  883. border-bottom: 1px solid var(--bs-light-bg-subtle) !important;
  884. box-sizing: border-box;
  885. vertical-align: middle;
  886. font-size: 14px;
  887. white-space: nowrap;
  888. }
  889. .uni-table-th {
  890. padding: px2rpx(6) px2rpx(15);
  891. box-sizing: border-box;
  892. vertical-align: middle;
  893. font-size: 14px;
  894. white-space: nowrap;
  895. word-break: keep-all;
  896. }
  897. .action-wrapper {
  898. max-width: 180px;
  899. white-space: normal;
  900. }
  901. .action-list {
  902. display: flex;
  903. flex-wrap: wrap;
  904. gap: 6px 5px;
  905. align-items: center;
  906. }
  907. .action-btn {
  908. color: var(--color-primary);
  909. text-decoration: underline;
  910. cursor: pointer;
  911. font-size: px2rpx(12);
  912. white-space: nowrap;
  913. }
  914. .action-toggle-btn {
  915. color: #909399;
  916. cursor: pointer;
  917. font-size: px2rpx(12);
  918. white-space: nowrap;
  919. }
  920. .expand-cell {
  921. padding: 0 !important;
  922. }
  923. }
  924. }
  925. .crm-chevron-down {
  926. transform: rotate(-90deg);
  927. cursor: pointer;
  928. }
  929. .mobile-table {
  930. :deep(.uni-table) {
  931. min-width: 0 !important;
  932. }
  933. }
  934. .detail-btn-mobile {
  935. background-color: #f0f0f0;
  936. color: var(--bs-heading-color);
  937. }
  938. /* 分页样式 */
  939. .pagination-container {
  940. margin: px2rpx(20) 0;
  941. display: flex;
  942. align-items: center;
  943. justify-content: flex-end;
  944. gap: px2rpx(20);
  945. position: relative;
  946. z-index: 10;
  947. background-color: transparent;
  948. .pagination {
  949. display: flex;
  950. align-items: center;
  951. //padding: px2rpx(10);
  952. }
  953. .page-item {
  954. display: flex;
  955. align-items: center;
  956. justify-content: center;
  957. padding: 0 px2rpx(12);
  958. min-width: px2rpx(32);
  959. height: px2rpx(30);
  960. background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
  961. border-radius: px2rpx(4);
  962. font-size: px2rpx(14);
  963. color: #606266;
  964. cursor: pointer;
  965. transition: all 0.3s;
  966. margin: 0 px2rpx(6);
  967. &:not(.disabled):hover {
  968. color: #cf1322;
  969. }
  970. &.disabled {
  971. opacity: 0.5;
  972. cursor: not-allowed;
  973. pointer-events: none;
  974. color: #c0c4cc;
  975. }
  976. }
  977. .page-numbers {
  978. display: flex;
  979. flex: 1;
  980. gap: px2rpx(8);
  981. }
  982. .arrow-left {
  983. transform: rotate(180deg);
  984. }
  985. .page-number {
  986. display: flex;
  987. align-items: center;
  988. justify-content: center;
  989. min-width: px2rpx(20);
  990. height: px2rpx(26);
  991. padding: 0 px2rpx(4);
  992. background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
  993. border-radius: px2rpx(4);
  994. font-size: px2rpx(12);
  995. color: #606266;
  996. cursor: pointer;
  997. transition: all 0.3s;
  998. font-weight: 500;
  999. &.ellipsis {
  1000. cursor: default;
  1001. background: transparent;
  1002. color: #c0c4cc;
  1003. font-weight: bold;
  1004. min-width: px2rpx(24);
  1005. }
  1006. &:not(.ellipsis):hover {
  1007. color: #cf1322;
  1008. }
  1009. &.active {
  1010. background-color: #cf1322;
  1011. color: var(--bs-emphasis-color);
  1012. border-color: #cf1322;
  1013. &:hover {
  1014. color: var(--bs-emphasis-color);
  1015. }
  1016. }
  1017. }
  1018. .pagination-info {
  1019. display: flex;
  1020. align-items: center;
  1021. gap: px2rpx(30);
  1022. font-size: px2rpx(16);
  1023. color: #909399;
  1024. }
  1025. .page-size-select {
  1026. display: flex;
  1027. align-items: center;
  1028. gap: px2rpx(10);
  1029. }
  1030. .page-size-value {
  1031. padding: px2rpx(6) px2rpx(20);
  1032. border: 1px solid #dcdfe6;
  1033. border-radius: px2rpx(8);
  1034. color: #606266;
  1035. }
  1036. }
  1037. @media screen and (max-width: 768px) {
  1038. .pagination {
  1039. flex-wrap: nowrap;
  1040. justify-content: center;
  1041. //width: 100%;
  1042. overflow-x: auto;
  1043. -webkit-overflow-scrolling: touch;
  1044. &::-webkit-scrollbar {
  1045. display: none;
  1046. }
  1047. }
  1048. .page-numbers {
  1049. flex: none;
  1050. gap: px2rpx(4);
  1051. }
  1052. .page-item {
  1053. padding: 0 px2rpx(8);
  1054. min-width: px2rpx(28);
  1055. margin: 0 px2rpx(2);
  1056. }
  1057. .page-number {
  1058. min-width: px2rpx(28);
  1059. padding: 0 px2rpx(4);
  1060. font-size: px2rpx(12);
  1061. &.ellipsis {
  1062. min-width: px2rpx(16);
  1063. padding: 0;
  1064. }
  1065. }
  1066. .pagination-info {
  1067. flex-direction: column;
  1068. gap: px2rpx(10);
  1069. }
  1070. }
  1071. .morebox{
  1072. width: 100%;
  1073. height: 100%;
  1074. display: flex;
  1075. align-items: center;
  1076. justify-content: center;
  1077. }
  1078. </style>