cwg-tabel.vue 35 KB

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