cwg-tabel.vue 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  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. 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. flex-shrink: 0;
  747. overflow: visible;
  748. }
  749. }
  750. }
  751. .table-empty-state {
  752. flex: 1;
  753. display: flex;
  754. align-items: center;
  755. justify-content: center;
  756. min-height: px2rpx(280);
  757. padding: px2rpx(24) px2rpx(20) px2rpx(40);
  758. box-sizing: border-box;
  759. }
  760. .action-wrapper {
  761. display: flex;
  762. justify-content: center;
  763. align-items: center;
  764. .action-trigger {
  765. display: flex;
  766. justify-content: center;
  767. align-items: center;
  768. cursor: pointer;
  769. padding: px2rpx(4);
  770. border-radius: px2rpx(4);
  771. transition: background-color 0.2s;
  772. &:hover {
  773. background-color: rgba(0, 0, 0, 0.05);
  774. }
  775. }
  776. }
  777. .table-loading-mask {
  778. width: 100%;
  779. height: 100%;
  780. // margin: 0 auto;
  781. display: flex;
  782. align-items: center;
  783. justify-content: center;
  784. }
  785. :deep(.uni-table-scroll) {
  786. width: 100%;
  787. max-height: calc(100vh - 375px);
  788. min-height: px2rpx(300);
  789. overflow-y: auto;
  790. overflow-x: auto;
  791. /* 强制显示滚动条并美化 */
  792. &::-webkit-scrollbar {
  793. width: 4px !important;
  794. height: 4px !important;
  795. display: block !important;
  796. /* 强制在某些webkit浏览器中显示 */
  797. background-color:yellow !important;
  798. }
  799. &::-webkit-scrollbar-track {
  800. background-color: #faf3f3;
  801. border-radius: 4px;
  802. }
  803. &::-webkit-scrollbar-thumb {
  804. background-color:#6a6a6a;
  805. border-radius: 4px;
  806. &:hover {
  807. background-color: #6a6a6a;
  808. }
  809. }
  810. }
  811. :deep(.uni-table) {
  812. border-radius: 8px;
  813. //box-shadow: 0 1px 4px rgba(0, 0, 0, 0.02);
  814. height: 100%;
  815. .uni-table-th {
  816. position: sticky;
  817. top: 0;
  818. z-index: 100;
  819. transition: all 0.3s;
  820. background-color: var(--table-th-color) !important;
  821. border-bottom: 1px solid var(--bs-light-bg-subtle) !important;
  822. color: #000 !important;
  823. padding-left: px2rpx(10);
  824. .header-content {
  825. display: flex;
  826. align-items: center;
  827. justify-content: center;
  828. gap: 4px;
  829. .sort-icon {
  830. display: inline-flex;
  831. cursor: pointer;
  832. }
  833. }
  834. &.sortable {
  835. cursor: pointer;
  836. &:hover .sort-icon .uni-icons {
  837. color: var(--color-primary) !important;
  838. }
  839. }
  840. &::after {
  841. display: none;
  842. }
  843. }
  844. .uni-table-tr {
  845. transition: background-color 0.2s ease;
  846. border-bottom: 1px solid var(--bs-light-bg-subtle) !important;
  847. color: var(--bs-emphasis-color) !important;
  848. // 奇数行背景颜色
  849. &:nth-child(odd) {
  850. // 暂时用一样的颜色
  851. background-color: var(--bs-light-bg-subtle);
  852. //background-color: var(--bs-body-bg);
  853. }
  854. // 偶数行背景颜色
  855. &:nth-child(even) {
  856. background-color: var(--bs-body-bg);
  857. }
  858. &:hover {
  859. background-color: var(--bs-light-bg-subtle) !important;
  860. }
  861. &:last-child {
  862. border-bottom: none !important;
  863. }
  864. }
  865. .summary-row {
  866. background-color: var(--table-th-color);
  867. font-weight: 600;
  868. .uni-table-td {
  869. border-top: 1px solid var(--table-th-color) !important;
  870. position: sticky;
  871. bottom: 0;
  872. z-index: 99;
  873. background-color: var(--table-th-color);
  874. }
  875. }
  876. .uni-table-td {
  877. padding: px2rpx(16) px2rpx(15);
  878. color: var(--bs-emphasis-color) !important;
  879. border-bottom: 1px solid var(--bs-light-bg-subtle) !important;
  880. box-sizing: border-box;
  881. vertical-align: middle;
  882. font-size: 14px;
  883. white-space: nowrap;
  884. }
  885. .uni-table-th {
  886. padding: px2rpx(6) px2rpx(15);
  887. box-sizing: border-box;
  888. vertical-align: middle;
  889. font-size: 14px;
  890. white-space: nowrap;
  891. word-break: keep-all;
  892. }
  893. .action-wrapper {
  894. max-width: 180px;
  895. white-space: normal;
  896. }
  897. .action-list {
  898. display: flex;
  899. flex-wrap: wrap;
  900. gap: 6px 5px;
  901. align-items: center;
  902. }
  903. .action-btn {
  904. color: var(--color-primary);
  905. text-decoration: underline;
  906. cursor: pointer;
  907. font-size: px2rpx(12);
  908. white-space: nowrap;
  909. }
  910. .action-toggle-btn {
  911. color: #909399;
  912. cursor: pointer;
  913. font-size: px2rpx(12);
  914. white-space: nowrap;
  915. }
  916. .expand-cell {
  917. padding: 0 !important;
  918. }
  919. }
  920. }
  921. .crm-chevron-down {
  922. transform: rotate(-90deg);
  923. cursor: pointer;
  924. }
  925. .mobile-table {
  926. :deep(.uni-table) {
  927. min-width: 0 !important;
  928. }
  929. }
  930. .detail-btn-mobile {
  931. background-color: #f0f0f0;
  932. color: var(--bs-heading-color);
  933. }
  934. /* 分页样式 */
  935. .pagination-container {
  936. margin: px2rpx(20) 0;
  937. display: flex;
  938. align-items: center;
  939. justify-content: flex-end;
  940. gap: px2rpx(20);
  941. position: relative;
  942. z-index: 10;
  943. background-color: transparent;
  944. .pagination {
  945. display: flex;
  946. align-items: center;
  947. //padding: px2rpx(10);
  948. }
  949. .page-item {
  950. display: flex;
  951. align-items: center;
  952. justify-content: center;
  953. padding: 0 px2rpx(12);
  954. min-width: px2rpx(32);
  955. height: px2rpx(30);
  956. background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
  957. border-radius: px2rpx(4);
  958. font-size: px2rpx(14);
  959. color: #606266;
  960. cursor: pointer;
  961. transition: all 0.3s;
  962. margin: 0 px2rpx(6);
  963. &:not(.disabled):hover {
  964. color: #cf1322;
  965. }
  966. &.disabled {
  967. opacity: 0.5;
  968. cursor: not-allowed;
  969. pointer-events: none;
  970. color: #c0c4cc;
  971. }
  972. }
  973. .page-numbers {
  974. display: flex;
  975. flex: 1;
  976. gap: px2rpx(8);
  977. }
  978. .arrow-left {
  979. transform: rotate(180deg);
  980. }
  981. .page-number {
  982. display: flex;
  983. align-items: center;
  984. justify-content: center;
  985. min-width: px2rpx(20);
  986. height: px2rpx(26);
  987. padding: 0 px2rpx(4);
  988. background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
  989. border-radius: px2rpx(4);
  990. font-size: px2rpx(12);
  991. color: #606266;
  992. cursor: pointer;
  993. transition: all 0.3s;
  994. font-weight: 500;
  995. &.ellipsis {
  996. cursor: default;
  997. background: transparent;
  998. color: #c0c4cc;
  999. font-weight: bold;
  1000. min-width: px2rpx(24);
  1001. }
  1002. &:not(.ellipsis):hover {
  1003. color: #cf1322;
  1004. }
  1005. &.active {
  1006. background-color: #cf1322;
  1007. color: var(--bs-emphasis-color);
  1008. border-color: #cf1322;
  1009. &:hover {
  1010. color: var(--bs-emphasis-color);
  1011. }
  1012. }
  1013. }
  1014. .pagination-info {
  1015. display: flex;
  1016. align-items: center;
  1017. gap: px2rpx(30);
  1018. font-size: px2rpx(16);
  1019. color: #909399;
  1020. }
  1021. .page-size-select {
  1022. display: flex;
  1023. align-items: center;
  1024. gap: px2rpx(10);
  1025. }
  1026. .page-size-value {
  1027. padding: px2rpx(6) px2rpx(20);
  1028. border: 1px solid #dcdfe6;
  1029. border-radius: px2rpx(8);
  1030. color: #606266;
  1031. }
  1032. }
  1033. @media screen and (max-width: 768px) {
  1034. .pagination {
  1035. flex-wrap: nowrap;
  1036. justify-content: center;
  1037. width: 100%;
  1038. overflow-x: auto;
  1039. -webkit-overflow-scrolling: touch;
  1040. &::-webkit-scrollbar {
  1041. display: none;
  1042. }
  1043. }
  1044. .page-numbers {
  1045. flex: none;
  1046. gap: px2rpx(4);
  1047. }
  1048. .page-item {
  1049. padding: 0 px2rpx(8);
  1050. min-width: px2rpx(28);
  1051. margin: 0 px2rpx(2);
  1052. }
  1053. .page-number {
  1054. min-width: px2rpx(28);
  1055. padding: 0 px2rpx(4);
  1056. font-size: px2rpx(12);
  1057. &.ellipsis {
  1058. min-width: px2rpx(16);
  1059. padding: 0;
  1060. }
  1061. }
  1062. .pagination-info {
  1063. flex-direction: column;
  1064. gap: px2rpx(10);
  1065. }
  1066. }
  1067. .morebox{
  1068. width: 100%;
  1069. height: 100%;
  1070. display: flex;
  1071. align-items: center;
  1072. justify-content: center;
  1073. }
  1074. </style>