cwg-tabel.vue 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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 v-if="getComputedMenuList(column.menuList, row).length > 0"
  41. :menuList="getComputedMenuList(column.menuList, row)" placement="bottom-end"
  42. @menuClick="(payload) => handleActionClick(payload, row)">
  43. <view class="action-trigger">
  44. <cwg-icon name="crm-ellipsis" :size="24" />
  45. </view>
  46. </cwg-droplist>
  47. </view>
  48. <template v-else-if="column.type === 'more'">
  49. <cwg-icon v-if="isMobile" name="crm-chevron-down" class="crm-chevron-down" :size="16" />
  50. </template>
  51. <template v-else>
  52. {{ formatCellValue(row[column.prop], column, row) }}
  53. </template>
  54. </uni-td>
  55. </uni-tr>
  56. <!-- 桌面端展开行(仅当非移动端且行展开时显示) -->
  57. <uni-tr v-if="!isMobile && expandedRows[rowIndex]" class="expand-row">
  58. <uni-td :colspan="columnSpan" class="expand-cell">
  59. <slot name="expand" :row="row" :rowIndex="rowIndex">
  60. <view class="default-expand-content">
  61. <text class="no-content">暂无展开内容</text>
  62. </view>
  63. </slot>
  64. </uni-td>
  65. </uni-tr>
  66. </template>
  67. <!-- 总计行 -->
  68. <uni-tr v-if="showSummary && tableData.length !== 0" class="summary-row">
  69. <uni-td v-for="(column, index) in displayColumns" :key="'summary-' + column.prop"
  70. :align="column.align || 'center'" class="summary-cell"
  71. :style="getCellStyle(column, currentSummaryData)">
  72. <!-- 当有 summaryMethod 时,按照返回的数组直接渲染 -->
  73. <template v-if="props.summaryMethod">
  74. <text>{{ computedSummaryRow[index] !== undefined ? computedSummaryRow[index] : '' }}</text>
  75. </template>
  76. <template v-else>
  77. <!-- 特定列的总计自定义插槽,例如 #summary-volume="{ row }" -->
  78. <template v-if="$slots['summary-' + column.prop]">
  79. <slot :name="'summary-' + column.prop" :row="currentSummaryData" :column="column"
  80. :index="index"></slot>
  81. </template>
  82. <!-- 如果没有特定插槽,尝试常规渲染 -->
  83. <template v-else>
  84. <template
  85. v-if="currentSummaryData && currentSummaryData[column.prop] !== undefined && currentSummaryData[column.prop] !== null">
  86. <!-- 如果有常规插槽,并且总计数据里有该字段的值,则复用常规插槽渲染 -->
  87. <slot v-if="column.slot" :name="column.slot" :row="currentSummaryData"
  88. :column="column" :index="index">
  89. {{ currentSummaryData[column.prop] }}
  90. </slot>
  91. <!-- 否则使用格式化函数 -->
  92. <text v-else>{{ formatCellValue(currentSummaryData[column.prop], column,
  93. currentSummaryData) }}</text>
  94. </template>
  95. <!-- 如果总计数据里没有该字段的值,第一列显示总计文本,其他留空 -->
  96. <text v-else>{{ index === 0 ? summaryText : '' }}</text>
  97. </template>
  98. </template>
  99. </uni-td>
  100. </uni-tr>
  101. </uni-table>
  102. </view>
  103. <view class="table-loading-mask">
  104. <uni-loading v-if="loading" />
  105. </view>
  106. <!-- 空状态 -->
  107. <view v-if="!loading && tableData.length === 0" style="width: 100%;">
  108. <cwg-empty-state />
  109. </view>
  110. <!-- 分页 -->
  111. <view class="pagination-container" v-if="showPagination && tableData.length > 0">
  112. <!-- <view class="pagination-info">
  113. <text>共 {{ pagination.total }} 条记录</text>
  114. <view v-if="showPageSize" class="page-size-select">
  115. <text>每页显示</text>
  116. <picker @change="handlePageSizeChange" :value="pageSizeIndex" :range="pageSizes">
  117. <view class="page-size-value">{{ pagination.pageSize }}条/页</view>
  118. </picker>
  119. </view>
  120. </view> -->
  121. <view class="pagination">
  122. <view class="page-item prev" :class="{ disabled: pagination.current === 1 }"
  123. @click="handlePageChange('prev')">
  124. <uni-icons type="arrowright" size="14" :color="pagination.current === 1 ? '#c0c4cc' : '#606266'"
  125. class="arrow-left" />
  126. </view>
  127. <view class="page-numbers">
  128. <view v-for="(page, index) in visiblePages" :key="index" class="page-number"
  129. :class="{ active: pagination.current === page, ellipsis: page === '...' }"
  130. @click="page !== '...' && handlePageChange(page)">
  131. {{ page }}
  132. </view>
  133. </view>
  134. <view class="page-item next" :class="{ disabled: pagination.current === pagination.pages }"
  135. @click="handlePageChange('next')">
  136. <uni-icons type="arrowright" size="14"
  137. :color="pagination.current === pagination.pages ? '#c0c4cc' : '#606266'" />
  138. </view>
  139. </view>
  140. </view>
  141. <!-- 移动端详情弹窗 -->
  142. <!-- <cwg-detail-popup v-model:visible="detailVisible" title="详情" :items="detailItems" /> -->
  143. <cwg-detail-popup v-model:visible="detailVisible" title="详情" :row="detailRow" :columns="detailColumns">
  144. <template v-for="col in detailColumns" :key="col.prop" #[`cell-${col.prop}`]="{ row, column }">
  145. <view v-if="col.type === 'file'">
  146. <cwg-file :path="row[column.prop]" />
  147. </view>
  148. <slot v-else-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 },
  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: '28rpx' },
  210. headerFontWeight: { type: [String, Number], default: 600 },
  211. headerHeight: { type: [String, Number], default: '64rpx' },
  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. // 是否跳转页面
  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. emit('go-pages', row)
  511. } else {
  512. if (props.pagesToDetail) {
  513. emit('go-pages', row)
  514. } else if (isMobile.value) {
  515. // 保存当前行和需要显示的列(有 prop 且有 label) pc 详情不展示操作按钮
  516. detailRow.value = { ...row, note: getNoteText(row, locale.value, userStore) }
  517. 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)
  518. detailVisible.value = true
  519. }
  520. }
  521. }
  522. const setDetailVisible = (visible) => {
  523. detailVisible.value = visible
  524. }
  525. // ========== 数据加载 ==========
  526. const loadData = async () => {
  527. if (props.data) {
  528. tableData.value = props.data
  529. if (props.summaryData) {
  530. internalSummaryData.value = props.summaryData
  531. }
  532. return
  533. }
  534. tableData.value = []
  535. if (loading.value) return
  536. loading.value = true
  537. try {
  538. const applyPaginationFromRes = (res) => {
  539. const page = res && res.page
  540. if (!page) return false
  541. if (typeof page.current === 'number') pagination.value.current = page.current
  542. if (typeof page.row === 'number') pagination.value.pageSize = page.row
  543. if (typeof page.rowTotal === 'number') pagination.value.total = page.rowTotal
  544. if (typeof page.pageTotal === 'number') pagination.value.pages = page.pageTotal
  545. else if (typeof pagination.value.total === 'number' && typeof pagination.value.pageSize === 'number') {
  546. pagination.value.pages = Math.ceil(pagination.value.total / pagination.value.pageSize)
  547. }
  548. return true
  549. }
  550. // 👇 修复后:使用解构获取最新的 queryParams,杜绝延迟
  551. const query = { ...props.queryParams };
  552. let startDate = "";
  553. let endDate = "";
  554. // 处理日期范围(用解构后的 query,绝对最新)
  555. if (!query.date || query.date.length === 0) {
  556. startDate = "";
  557. endDate = "";
  558. } else {
  559. startDate = query.date[0] || "";
  560. endDate = query.date[1] || "";
  561. }
  562. // 组装请求参数
  563. const params = {
  564. page: {
  565. current: pagination.value.current,
  566. row: pagination.value.pageSize
  567. },
  568. ...query, // 用解构后的最新 query
  569. startDate,
  570. endDate
  571. };
  572. // 添加排序参数
  573. if (sortState.value.prop && sortState.value.order) {
  574. params.sort = { field: sortState.value.prop, order: sortState.value.order }
  575. }
  576. const res = await props.api(params)
  577. if (res.code === 200 || res.code === 0 || res.code === 10000) {
  578. if (res.sum) {
  579. internalSummaryData.value = res.sum
  580. } else {
  581. internalSummaryData.value = null
  582. }
  583. const data = res.data || res
  584. const hasPage = applyPaginationFromRes(res)
  585. if (Array.isArray(data)) {
  586. tableData.value = data
  587. if (!hasPage) {
  588. pagination.value.total = data.length
  589. pagination.value.pages = 1
  590. }
  591. } else if (data.list || data.records) {
  592. tableData.value = data.list || data.records
  593. if (!hasPage) {
  594. pagination.value.total = data.total || data.list?.length || 0
  595. pagination.value.pages = data.pages || Math.ceil(pagination.value.total / pagination.value.pageSize)
  596. }
  597. } else {
  598. tableData.value = []
  599. }
  600. emit('load-success', res)
  601. } else {
  602. throw new Error(res.message || '加载失败')
  603. }
  604. } catch (error) {
  605. console.error('表格数据加载失败:', error)
  606. uni.showToast({
  607. title: error.message || '加载失败',
  608. icon: 'none'
  609. })
  610. emit('load-error', error)
  611. } finally {
  612. loading.value = false
  613. pageLoading.value = false
  614. }
  615. }
  616. // 刷新表格
  617. const refreshTable = () => {
  618. pagination.value.current = 1
  619. loadData()
  620. }
  621. const reload = () => {
  622. loadData()
  623. }
  624. const pageLoading = ref(false)
  625. // 分页变化
  626. const handlePageChange = (page) => {
  627. if (pageLoading.value) return
  628. pageLoading.value = true
  629. if (page === 'prev') {
  630. if (pagination.value.current > 1) pagination.value.current--
  631. else return
  632. } else if (page === 'next') {
  633. if (pagination.value.current < pagination.value.pages) pagination.value.current++
  634. else return
  635. } else {
  636. pagination.value.current = page
  637. }
  638. loadData()
  639. emit('page-change', pagination.value)
  640. }
  641. // 每页条数变化
  642. const handlePageSizeChange = (e) => {
  643. const size = props.pageSizes[e.detail.value]
  644. pagination.value.pageSize = size
  645. pagination.value.current = 1
  646. loadData()
  647. }
  648. // 选择变化
  649. const handleSelectionChange = (e) => {
  650. selectedItems.value = e.detail.value
  651. emit('selection-change', selectedItems.value)
  652. }
  653. // 获取选中项
  654. const getSelectedItems = () => selectedItems.value
  655. const clearSelection = () => { selectedItems.value = [] }
  656. // ========== 移动端检测 ==========
  657. const checkIsMobile = () => {
  658. // 适配 uni-app 环境
  659. // #ifdef H5
  660. const width = window.innerWidth
  661. isMobile.value = width < 991
  662. // #endif
  663. // #ifndef H5
  664. const systemInfo = uni.getSystemInfoSync()
  665. isMobile.value = systemInfo.windowWidth < 991
  666. // #endif
  667. }
  668. // 监听窗口大小变化(仅 H5)
  669. // #ifdef H5
  670. const handleResize = () => {
  671. checkIsMobile()
  672. }
  673. // #endif
  674. // ========== 监听参数变化 ==========
  675. watch(() => props.data, (newData) => {
  676. if (newData) {
  677. tableData.value = newData
  678. }
  679. }, { deep: true, immediate: true })
  680. watch(() => props.summaryData, (newSum) => {
  681. if (props.data && newSum) {
  682. internalSummaryData.value = newSum
  683. }
  684. }, { deep: true, immediate: true })
  685. watch(() => props.queryParams, () => {
  686. nextTick(() => {
  687. // refreshTable()
  688. })
  689. }, { deep: true })
  690. watch(() => props.api, () => {
  691. nextTick(() => {
  692. refreshTable()
  693. })
  694. }, { deep: true })
  695. // ========== 生命周期 ==========
  696. onMounted(() => {
  697. checkIsMobile()
  698. // #ifdef H5
  699. window.addEventListener('resize', handleResize)
  700. // #endif
  701. if (props.immediate) {
  702. loadData()
  703. }
  704. })
  705. onUnmounted(() => {
  706. // #ifdef H5
  707. window.removeEventListener('resize', handleResize)
  708. // #endif
  709. })
  710. // 暴露方法
  711. defineExpose({
  712. refreshTable,
  713. reload,
  714. getSelectedItems,
  715. clearSelection,
  716. loadData,
  717. tableData,
  718. toggleRowExpand,
  719. pagination,
  720. setDetailVisible
  721. })
  722. </script>
  723. <style scoped lang="scss">
  724. @import "@/uni.scss";
  725. .table-container {
  726. width: 100%;
  727. overflow-x: auto;
  728. -webkit-overflow-scrolling: touch;
  729. margin-top: px2rpx(20);
  730. max-height: calc(100vh - 209px);
  731. color: var(--color-slate-800);
  732. .action-wrapper {
  733. display: flex;
  734. justify-content: center;
  735. align-items: center;
  736. .action-trigger {
  737. display: flex;
  738. justify-content: center;
  739. align-items: center;
  740. cursor: pointer;
  741. padding: px2rpx(4);
  742. border-radius: px2rpx(4);
  743. transition: background-color 0.2s;
  744. &:hover {
  745. background-color: rgba(0, 0, 0, 0.05);
  746. }
  747. }
  748. }
  749. .table-loading-mask {
  750. width: 100%;
  751. height: 100%;
  752. // margin: 0 auto;
  753. display: flex;
  754. align-items: center;
  755. justify-content: center;
  756. }
  757. :deep(.uni-table-scroll) {
  758. width: 100%;
  759. max-height: calc(100vh - 375px);
  760. //min-height: 300px;
  761. overflow-y: auto;
  762. overflow-x: auto;
  763. /* 强制显示滚动条并美化 */
  764. &::-webkit-scrollbar {
  765. width: 4px !important;
  766. height: 4px !important;
  767. display: block !important;
  768. /* 强制在某些webkit浏览器中显示 */
  769. background-color: #ccc !important;
  770. }
  771. &::-webkit-scrollbar-track {
  772. background-color: #ccc;
  773. border-radius: 4px;
  774. }
  775. &::-webkit-scrollbar-thumb {
  776. background-color:#ccc;
  777. border-radius: 4px;
  778. &:hover {
  779. background-color: #ccc;
  780. }
  781. }
  782. }
  783. :deep(.uni-table) {
  784. border-radius: 8px;
  785. box-shadow: 0 1px 4px rgba(0, 0, 0, 0.02);
  786. .uni-table-th {
  787. position: sticky;
  788. top: 0;
  789. z-index: 100;
  790. transition: all 0.3s;
  791. background-color: rgba(var(--bs-danger-rgb), var(--bs-bg-opacity)) !important;
  792. border-bottom: 1px solid var(--bs-light-bg-subtle) !important;
  793. color: rgb(var(--bs-white-rgb)) !important;
  794. .header-content {
  795. display: flex;
  796. align-items: center;
  797. justify-content: center;
  798. gap: 4px;
  799. .sort-icon {
  800. display: inline-flex;
  801. cursor: pointer;
  802. }
  803. }
  804. &.sortable {
  805. cursor: pointer;
  806. &:hover .sort-icon .uni-icons {
  807. color: var(--color-primary) !important;
  808. }
  809. }
  810. &::after {
  811. display: none;
  812. }
  813. }
  814. .uni-table-tr {
  815. transition: background-color 0.2s ease;
  816. border-bottom: 1px solid var(--bs-light-bg-subtle) !important;
  817. color: var(--bs-emphasis-color) !important;
  818. // 奇数行背景颜色
  819. &:nth-child(odd) {
  820. background-color: var(--bs-light-bg-subtle);
  821. }
  822. // 偶数行背景颜色
  823. &:nth-child(even) {
  824. background-color: var(--bs-body-bg);
  825. }
  826. &:hover {
  827. background-color: var(--bs-light-bg-subtle) !important;
  828. }
  829. &:last-child {
  830. border-bottom: none !important;
  831. }
  832. }
  833. .summary-row {
  834. background-color: var(--bs-light-bg-subtle);
  835. font-weight: 600;
  836. .uni-table-td {
  837. border-top: 1px solid var(--bs-light-bg-subtle) !important;
  838. position: sticky;
  839. bottom: 0;
  840. z-index: 99;
  841. background-color: var(--bs-light-bg-subtle);
  842. }
  843. }
  844. .uni-table-td {
  845. padding: px2rpx(16) px2rpx(5);
  846. color: var(--bs-emphasis-color) !important;
  847. border-bottom: 1px solid var(--bs-light-bg-subtle) !important;
  848. box-sizing: border-box;
  849. vertical-align: middle;
  850. font-size: 14px;
  851. white-space: nowrap;
  852. }
  853. .uni-table-th {
  854. padding: px2rpx(6) px2rpx(5);
  855. box-sizing: border-box;
  856. vertical-align: middle;
  857. font-size: 14px;
  858. white-space: nowrap;
  859. word-break: keep-all;
  860. }
  861. .action-wrapper {
  862. max-width: 180px;
  863. white-space: normal;
  864. }
  865. .action-list {
  866. display: flex;
  867. flex-wrap: wrap;
  868. gap: 6px 5px;
  869. align-items: center;
  870. }
  871. .action-btn {
  872. color: var(--color-primary);
  873. text-decoration: underline;
  874. cursor: pointer;
  875. font-size: px2rpx(12);
  876. white-space: nowrap;
  877. }
  878. .action-toggle-btn {
  879. color: #909399;
  880. cursor: pointer;
  881. font-size: px2rpx(12);
  882. white-space: nowrap;
  883. }
  884. .expand-cell {
  885. padding: 0 !important;
  886. }
  887. }
  888. }
  889. .crm-chevron-down {
  890. transform: rotate(-90deg);
  891. cursor: pointer;
  892. }
  893. .mobile-table {
  894. :deep(.uni-table) {
  895. min-width: 0 !important;
  896. }
  897. }
  898. .detail-btn-mobile {
  899. background-color: #f0f0f0;
  900. color: var(--bs-heading-color);
  901. }
  902. /* 分页样式 */
  903. .pagination-container {
  904. margin: px2rpx(20) 0;
  905. display: flex;
  906. align-items: center;
  907. justify-content: flex-end;
  908. gap: px2rpx(20);
  909. position: relative;
  910. z-index: 10;
  911. background-color: transparent;
  912. .pagination {
  913. display: flex;
  914. align-items: center;
  915. //padding: px2rpx(10);
  916. }
  917. .page-item {
  918. display: flex;
  919. align-items: center;
  920. justify-content: center;
  921. padding: 0 px2rpx(12);
  922. min-width: px2rpx(32);
  923. height: px2rpx(30);
  924. background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
  925. border-radius: px2rpx(4);
  926. font-size: px2rpx(14);
  927. color: #606266;
  928. cursor: pointer;
  929. transition: all 0.3s;
  930. margin: 0 px2rpx(6);
  931. &:not(.disabled):hover {
  932. color: #cf1322;
  933. }
  934. &.disabled {
  935. opacity: 0.5;
  936. cursor: not-allowed;
  937. pointer-events: none;
  938. color: #c0c4cc;
  939. }
  940. }
  941. .page-numbers {
  942. display: flex;
  943. flex: 1;
  944. gap: px2rpx(8);
  945. }
  946. .arrow-left {
  947. transform: rotate(180deg);
  948. }
  949. .page-number {
  950. display: flex;
  951. align-items: center;
  952. justify-content: center;
  953. min-width: px2rpx(20);
  954. height: px2rpx(26);
  955. padding: 0 px2rpx(4);
  956. background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
  957. border-radius: px2rpx(4);
  958. font-size: px2rpx(12);
  959. color: #606266;
  960. cursor: pointer;
  961. transition: all 0.3s;
  962. font-weight: 500;
  963. &.ellipsis {
  964. cursor: default;
  965. background: transparent;
  966. color: #c0c4cc;
  967. font-weight: bold;
  968. min-width: px2rpx(24);
  969. }
  970. &:not(.ellipsis):hover {
  971. color: #cf1322;
  972. }
  973. &.active {
  974. background-color: #cf1322;
  975. color: var(--bs-emphasis-color);
  976. border-color: #cf1322;
  977. &:hover {
  978. color: var(--bs-emphasis-color);
  979. }
  980. }
  981. }
  982. .pagination-info {
  983. display: flex;
  984. align-items: center;
  985. gap: px2rpx(30);
  986. font-size: px2rpx(16);
  987. color: #909399;
  988. }
  989. .page-size-select {
  990. display: flex;
  991. align-items: center;
  992. gap: px2rpx(10);
  993. }
  994. .page-size-value {
  995. padding: px2rpx(6) px2rpx(20);
  996. border: 1px solid #dcdfe6;
  997. border-radius: px2rpx(8);
  998. color: #606266;
  999. }
  1000. }
  1001. @media screen and (max-width: 768px) {
  1002. .pagination {
  1003. flex-wrap: nowrap;
  1004. justify-content: center;
  1005. width: 100%;
  1006. overflow-x: auto;
  1007. -webkit-overflow-scrolling: touch;
  1008. &::-webkit-scrollbar {
  1009. display: none;
  1010. }
  1011. }
  1012. .page-numbers {
  1013. flex: none;
  1014. gap: px2rpx(4);
  1015. }
  1016. .page-item {
  1017. padding: 0 px2rpx(8);
  1018. min-width: px2rpx(28);
  1019. margin: 0 px2rpx(2);
  1020. }
  1021. .page-number {
  1022. min-width: px2rpx(28);
  1023. padding: 0 px2rpx(4);
  1024. font-size: px2rpx(12);
  1025. &.ellipsis {
  1026. min-width: px2rpx(16);
  1027. padding: 0;
  1028. }
  1029. }
  1030. .pagination-info {
  1031. flex-direction: column;
  1032. gap: px2rpx(10);
  1033. }
  1034. }
  1035. </style>