cwg-tabel.vue 37 KB

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