cwg-tabel.vue 37 KB

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