cwg-tabel.vue 38 KB

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