cwg-tabel.vue 38 KB

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