cwg-tabel.vue 36 KB

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