cwg-tabel.vue 29 KB

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