cwg-tabel.vue 35 KB

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