| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766 |
- <template>
- <view>
- <!-- 统一表格容器,根据屏幕宽度自适应 -->
- <view class="table-container" :class="{ 'mobile-table': isMobile }">
- <uni-table :type="selectionType" :border="false" @selection-change="handleSelectionChange" emptyText="">
- <!-- 表头:根据设备类型显示不同的列 -->
- <uni-tr class="table-header">
- <uni-th v-for="column in displayColumns" :key="column.prop" :align="column.align || 'center'"
- :width="column.width || '200'" :class="[headerClass, { sortable: column.sortable }]"
- :style="getHeaderStyle(column)" @click="column.sortable && handleSort(column)">
- <view class="header-content">
- {{ column.label }}
- <view v-if="column.sortable" class="sort-icon">
- <uni-icons :type="getSortIcon(column)" :size="14" color="#999" />
- </view>
- </view>
- </uni-th>
- </uni-tr>
- <!-- 表格主体 -->
- <template v-for="(row, rowIndex) in tableData" :key="rowIndex">
- <uni-tr>
- <!-- 数据列:根据设备类型动态渲染 -->
- <uni-td v-for="column in displayColumns" :key="column.prop" :align="column.align || 'center'"
- :class="getCellClass(column, row)" :style="getCellStyle(column, row)"
- @click="openRowDetail(row)">
- <template v-if="column.slot">
- <slot :name="column.slot" :row="row" :column="column" :index="rowIndex">
- {{ row[column.prop] }}
- </slot>
- </template>
- <uni-tag v-else-if="column.type === 'tag'" :text="formatTagText(row[column.prop], column)"
- :type="formatTagType(row[column.prop], column)" size="small" />
- <view v-else-if="column.type === 'file'">
- <cwg-file :path="row[column.prop]" />
- </view>
- <cwg-icon v-else-if="column.type === 'more'" name="crm-chevron-down"
- class="crm-chevron-down" :size="16" color="#007" />
- <template v-else>
- {{ formatCellValue(row[column.prop], column, row) }}
- </template>
- </uni-td>
- </uni-tr>
- <!-- 桌面端展开行(仅当非移动端且行展开时显示) -->
- <uni-tr v-if="!isMobile && expandedRows[rowIndex]" class="expand-row">
- <uni-td :colspan="columnSpan" class="expand-cell">
- <slot name="expand" :row="row" :rowIndex="rowIndex">
- <view class="default-expand-content">
- <text class="no-content">暂无展开内容</text>
- </view>
- </slot>
- </uni-td>
- </uni-tr>
- </template>
- </uni-table>
- </view>
- <!-- 空状态 -->
- <view v-if="tableData.length === 0">
- <cwg-empty-state />
- </view>
- <!-- 分页 -->
- <view class="pagination-container" v-if="showPagination && tableData.length > 0">
- <view class="pagination-info">
- <text>共 {{ pagination.total }} 条记录</text>
- <view v-if="showPageSize" class="page-size-select">
- <text>每页显示</text>
- <picker @change="handlePageSizeChange" :value="pageSizeIndex" :range="pageSizes">
- <view class="page-size-value">{{ pagination.pageSize }}条/页</view>
- </picker>
- </view>
- </view>
- <view class="pagination">
- <view class="page-item prev" :class="{ disabled: pagination.current === 1 }"
- @click="handlePageChange('prev')">
- <uni-icons type="arrowleft" size="16" color="#666" />
- <text>上一页</text>
- </view>
- <view class="page-numbers">
- <view v-for="page in visiblePages" :key="page" class="page-number"
- :class="{ active: pagination.current === page }" @click="handlePageChange(page)">
- {{ page }}
- </view>
- </view>
- <view class="page-item next" :class="{ disabled: pagination.current === pagination.pages }"
- @click="handlePageChange('next')">
- <text>下一页</text>
- <uni-icons type="arrowright" size="16" color="#666" />
- </view>
- </view>
- </view>
- <!-- 移动端详情弹窗 -->
- <cwg-detail-popup v-model:visible="detailVisible" title="详情" :items="detailItems" />
- </view>
- </template>
- <script setup>
- import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
- const props = defineProps({
- /**
- * 表格列配置(columns 数组中每一项是一个列配置对象)
- * - prop: 字段名,对应 row[prop],用于取值/排序/详情展示
- * - label: 表头显示文本(也会作为详情弹窗的 label)
- * - align: 对齐方式('left' | 'center' | 'right')
- * - width: 列宽(设置后该列固定宽度;未设置则自适应
- * - slot: 自定义渲染插槽名(<template #xxx="{ row, column, index }">),优先级最高
- * - formatter: ({ value, row }) => string | number,自定义格式化显示值(无 slot 时生效)
- * - sortable: 是否可排序(点击表头切换 asc/desc)
- * - headerStyle: 表头样式(对象),会合并到表头 style
- * - cellStyle: 单元格样式(对象或函数({ row, column }) => style)
- * - cellClass: 单元格 class(string 或函数({ row, column }) => string | string[])
- * - isTabel: false 时不在表格中显示该列,但仍会在“详情弹窗”中显示
- * - type: 内置渲染类型
- * - 'tag': 使用 uni-tag 渲染,搭配 tagMap/tagTypeMap
- * - 'file': 使用 cwg-file 渲染
- * - 'more': 展示“更多”图标(用于移动端点击查看详情等)
- * - 'date': 日期格式化(搭配 dateFormat)
- * - tagMap: 标签映射对象
- * - tagTypeMap: 标签类型映射对象
- * - dateFormat: 日期格式
- * */
- columns: { type: Array, required: true, default: () => [] },
- // 移动端配置
- mobilePrimaryCount: { type: Number, default: 3 },
- // 参数如columns
- mobilePrimaryFields: { type: Array, default: () => [] },
- // API 请求函数
- api: { type: Function, required: true },
- // 查询参数
- queryParams: { type: Object, default: () => ({}) },
- // 是否立即加载
- immediate: { type: Boolean, default: true },
- // 选择类型:'selection' | null
- selectionType: { type: String, default: null },
- // 是否显示每页条数选择
- showPageSize: { type: Boolean, default: true },
- // 是否显示分页
- showPagination: { type: Boolean, default: true },
- isViewDetail: { type: Boolean, default: true },
- // 每页条数选项
- pageSizes: { type: Array, default: () => [10, 20, 30, 50, 100] },
- // 默认每页条数
- defaultPageSize: { type: Number, default: 10 },
- // 表头样式自定义
- headerBackground: { type: String, default: '#fff' },
- headerColor: { type: String, default: 'var(--color-slate-800)' },
- headerFontSize: { type: [String, Number], default: '14rpx' },
- headerFontWeight: { type: [String, Number], default: 600 },
- headerHeight: { type: [String, Number], default: '40rpx' },
- headerClass: { type: [String, Array], default: '' },
- headerStyle: { type: Object, default: () => ({}) },
- stickyHeader: { type: Boolean, default: true },
- stickyOffset: { type: [String, Number], default: '0' },
- isPages: { type: Boolean, default: false },
- })
- const emit = defineEmits([
- 'selection-change',
- 'action-click',
- 'page-change',
- 'load-success',
- 'load-error',
- 'sort-change',
- 'go-pages'
- ])
- // ========== 响应式状态 ==========
- const tableData = ref([])
- const selectedItems = ref([])
- const detailVisible = ref(false)
- const detailItems = ref([])
- const pagination = ref({
- current: 1,
- pageSize: props.defaultPageSize,
- total: 0,
- pages: 0
- })
- const loading = ref(false)
- const expandedRows = ref({})
- // 移动端检测
- const isMobile = ref(false)
- // 排序状态
- const sortState = ref({ prop: '', order: '' }) // order: 'asc' | 'desc' | ''
- // ========== 计算属性 ==========
- // 显示的列(根据设备类型)
- const displayColumns = computed(() => {
- const filterForTable = (cols) => (cols || []).filter((c) => c && c.isTabel !== false)
- const normalizeColumns = (cols) => {
- if (!Array.isArray(cols)) return []
- if (cols.length === 0) return []
- const first = cols[0]
- if (typeof first === 'string') {
- return cols
- .map((prop) => props.columns.find((c) => c && c.prop === prop))
- .filter(Boolean)
- }
- return cols
- }
- if (!isMobile.value) return filterForTable(normalizeColumns(props.columns))
- if (props.mobilePrimaryFields && props.mobilePrimaryFields.length) {
- return filterForTable(normalizeColumns(props.mobilePrimaryFields))
- }
- return filterForTable(normalizeColumns(props.columns.slice(0, props.mobilePrimaryCount)))
- })
- // 列跨度(用于展开行)
- const columnSpan = computed(() => {
- let span = displayColumns.value.length
- if (props.showOperation) span += 1
- return span
- })
- // 每页条数索引
- const pageSizeIndex = computed(() => {
- return props.pageSizes.indexOf(pagination.value.pageSize)
- })
- // 可见页码
- const visiblePages = computed(() => {
- const maxVisible = 5
- const half = Math.floor(maxVisible / 2)
- let start = Math.max(1, pagination.value.current - half)
- let end = Math.min(pagination.value.pages, start + maxVisible - 1)
- if (end - start + 1 < maxVisible) {
- start = Math.max(1, end - maxVisible + 1)
- }
- return Array.from({ length: end - start + 1 }, (_, i) => start + i)
- })
- // ========== 工具函数 ==========
- // 获取表头样式
- const getHeaderStyle = (column) => {
- const baseStyle = {
- backgroundColor: props.headerBackground,
- color: props.headerColor,
- fontSize: typeof props.headerFontSize === 'number' ? props.headerFontSize + 'rpx' : props.headerFontSize,
- fontWeight: props.headerFontWeight,
- height: typeof props.headerHeight === 'number' ? props.headerHeight + 'rpx' : props.headerHeight,
- lineHeight: typeof props.headerHeight === 'number' ? props.headerHeight + 'rpx' : props.headerHeight,
- ...props.headerStyle
- }
- if (props.stickyHeader) {
- baseStyle.position = 'sticky'
- baseStyle.top = props.stickyOffset
- baseStyle.zIndex = 100
- }
- if (column.width) {
- const w = typeof column.width === 'number' ? column.width + 'px' : column.width
- baseStyle.width = w
- baseStyle.minWidth = w
- baseStyle.maxWidth = w
- }
- if (column.headerStyle) {
- Object.assign(baseStyle, column.headerStyle)
- }
- return baseStyle
- }
- // 获取单元格样式
- const getCellStyle = (column, row) => {
- const style = {}
- if (column.width) {
- const w = typeof column.width === 'number' ? column.width + 'px' : column.width
- style.width = w
- style.minWidth = w
- style.maxWidth = w
- style.whiteSpace = 'nowrap'
- style.overflow = 'hidden'
- style.textOverflow = 'ellipsis'
- }
- if (column.cellStyle) {
- if (typeof column.cellStyle === 'function') {
- Object.assign(style, column.cellStyle({ row, column }))
- } else {
- Object.assign(style, column.cellStyle)
- }
- }
- return style
- }
- // 获取单元格类名
- const getCellClass = (column, row) => {
- const classes = []
- if (column.cellClass) {
- if (typeof column.cellClass === 'function') {
- const result = column.cellClass({ row, column })
- if (result) {
- if (Array.isArray(result)) {
- classes.push(...result)
- } else {
- classes.push(result)
- }
- }
- } else {
- classes.push(column.cellClass)
- }
- }
- return classes.join(' ')
- }
- // 格式化单元格值
- const formatCellValue = (value, column, row) => {
- if (column.formatter) {
- return column.formatter({ value, row })
- }
- if (column.type === 'date' && value) {
- return formatDate(value, column.dateFormat || 'YYYY-MM-DD HH:mm:ss')
- }
- if (value === null || value === undefined) {
- return '-'
- }
- return value
- }
- // 格式化标签文本
- const formatTagText = (value, column) => {
- if (column.tagMap && column.tagMap[value]) {
- return column.tagMap[value]
- }
- return value || '-'
- }
- // 格式化标签类型
- const formatTagType = (value, column) => {
- if (column.tagTypeMap && column.tagTypeMap[value]) {
- return column.tagTypeMap[value]
- }
- return 'default'
- }
- // 格式化日期
- const formatDate = (date, format) => {
- if (!date) return '-'
- const d = new Date(date)
- const year = d.getFullYear()
- const month = String(d.getMonth() + 1).padStart(2, '0')
- const day = String(d.getDate()).padStart(2, '0')
- const hour = String(d.getHours()).padStart(2, '0')
- const minute = String(d.getMinutes()).padStart(2, '0')
- const second = String(d.getSeconds()).padStart(2, '0')
- return format
- .replace('YYYY', year)
- .replace('MM', month)
- .replace('DD', day)
- .replace('HH', hour)
- .replace('mm', minute)
- .replace('ss', second)
- }
- // 排序图标
- const getSortIcon = (column) => {
- if (sortState.value.prop !== column.prop) return 'arrow-up'
- return sortState.value.order === 'asc' ? 'arrow-up' : 'arrow-down'
- }
- // 处理排序
- const handleSort = (column) => {
- if (!column.sortable) return
- let newOrder = ''
- if (sortState.value.prop === column.prop) {
- if (sortState.value.order === '') newOrder = 'asc'
- else if (sortState.value.order === 'asc') newOrder = 'desc'
- else newOrder = ''
- } else {
- newOrder = 'asc'
- }
- sortState.value = { prop: newOrder ? column.prop : '', order: newOrder }
- emit('sort-change', { prop: sortState.value.prop, order: sortState.value.order })
- refreshTable()
- }
- // 展开行切换
- const toggleRowExpand = (rowIndex) => {
- const key = rowIndex
- if (expandedRows.value[key]) {
- expandedRows.value[key] = false
- } else {
- expandedRows.value = {}
- expandedRows.value[key] = true
- }
- emit('expand-change', { rowIndex, expanded: expandedRows.value[key] })
- }
- // 打开详情弹窗(移动端使用)
- const openRowDetail = (row) => {
- if (props.isPages) {
- emit('go-pages', row)
- } else {
- detailItems.value = props.columns
- .filter((column) => column && column.prop && column.label)
- .map((column) => ({
- label: column.label,
- value: String(formatCellValue(row[column.prop], column, row))
- }))
- detailVisible.value = true
- }
- }
- // ========== 数据加载 ==========
- const loadData = async () => {
- if (loading.value) return
- loading.value = true
- try {
- const applyPaginationFromRes = (res) => {
- const page = res && res.page
- if (!page) return false
- if (typeof page.current === 'number') pagination.value.current = page.current
- if (typeof page.row === 'number') pagination.value.pageSize = page.row
- if (typeof page.rowTotal === 'number') pagination.value.total = page.rowTotal
- if (typeof page.pageTotal === 'number') pagination.value.pages = page.pageTotal
- else if (typeof pagination.value.total === 'number' && typeof pagination.value.pageSize === 'number') {
- pagination.value.pages = Math.ceil(pagination.value.total / pagination.value.pageSize)
- }
- return true
- }
- const params = {
- page: {
- current: pagination.value.current,
- row: pagination.value.pageSize
- },
- ...props.queryParams
- }
- // 添加排序参数
- if (sortState.value.prop && sortState.value.order) {
- params.sort = { field: sortState.value.prop, order: sortState.value.order }
- }
- const res = await props.api(params)
- if (res.code === 200 || res.code === 0) {
- const data = res.data || res
- const hasPage = applyPaginationFromRes(res)
- if (Array.isArray(data)) {
- tableData.value = data
- if (!hasPage) {
- pagination.value.total = data.length
- pagination.value.pages = 1
- }
- } else if (data.list || data.records) {
- tableData.value = data.list || data.records
- if (!hasPage) {
- pagination.value.total = data.total || data.list?.length || 0
- pagination.value.pages = data.pages || Math.ceil(pagination.value.total / pagination.value.pageSize)
- }
- } else {
- tableData.value = []
- }
- emit('load-success', res)
- } else {
- throw new Error(res.message || '加载失败')
- }
- } catch (error) {
- console.error('表格数据加载失败:', error)
- uni.showToast({
- title: error.message || '加载失败',
- icon: 'none'
- })
- emit('load-error', error)
- } finally {
- loading.value = false
- }
- }
- // 刷新表格
- const refreshTable = () => {
- pagination.value.current = 1
- loadData()
- }
- const reload = () => {
- loadData()
- }
- // 分页变化
- const handlePageChange = (page) => {
- if (page === 'prev') {
- if (pagination.value.current > 1) pagination.value.current--
- else return
- } else if (page === 'next') {
- if (pagination.value.current < pagination.value.pages) pagination.value.current++
- else return
- } else {
- pagination.value.current = page
- }
- loadData()
- emit('page-change', pagination.value)
- }
- // 每页条数变化
- const handlePageSizeChange = (e) => {
- const size = props.pageSizes[e.detail.value]
- pagination.value.pageSize = size
- pagination.value.current = 1
- loadData()
- }
- // 选择变化
- const handleSelectionChange = (e) => {
- selectedItems.value = e.detail.value
- emit('selection-change', selectedItems.value)
- }
- // 获取选中项
- const getSelectedItems = () => selectedItems.value
- const clearSelection = () => { selectedItems.value = [] }
- // ========== 移动端检测 ==========
- const checkIsMobile = () => {
- // 适配 uni-app 环境
- // #ifdef H5
- const width = window.innerWidth
- isMobile.value = width < 991
- // #endif
- // #ifndef H5
- const systemInfo = uni.getSystemInfoSync()
- isMobile.value = systemInfo.windowWidth < 991
- // #endif
- }
- // 监听窗口大小变化(仅 H5)
- // #ifdef H5
- const handleResize = () => {
- checkIsMobile()
- }
- // #endif
- // ========== 监听参数变化 ==========
- watch(() => props.queryParams, () => {
- refreshTable()
- }, { deep: true })
- // ========== 生命周期 ==========
- onMounted(() => {
- checkIsMobile()
- // #ifdef H5
- window.addEventListener('resize', handleResize)
- // #endif
- if (props.immediate) {
- loadData()
- }
- })
- onUnmounted(() => {
- // #ifdef H5
- window.removeEventListener('resize', handleResize)
- // #endif
- })
- // 暴露方法
- defineExpose({
- refreshTable,
- reload,
- getSelectedItems,
- clearSelection,
- loadData,
- tableData,
- toggleRowExpand,
- pagination
- })
- </script>
- <style scoped lang="scss">
- @import "@/uni.scss";
- .table-container {
- width: 100%;
- // overflow-x: auto;
- // -webkit-overflow-scrolling: touch;
- max-height: calc(100vh - 209px);
- color: var(--color-slate-800);
- :deep(.uni-table-scroll) {
- width: 100%;
- max-height: calc(100vh - 375px);
- // overflow: auto;
- }
- :deep(.uni-table) {
- min-height: px2rpx(100) !important;
- .uni-table-th {
- position: sticky;
- top: 0;
- z-index: 100;
- transition: all 0.3s;
- .header-content {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 4px;
- .sort-icon {
- display: inline-flex;
- cursor: pointer;
- }
- }
- &.sortable {
- cursor: pointer;
- &:hover .sort-icon .uni-icons {
- color: var(--color-primary) !important;
- }
- }
- &::after {
- display: none;
- }
- }
- .uni-table-tr {
- &:last-child {
- border-bottom: none !important;
- }
- .uni-table-th {
- border-bottom: 1px solid #141d22 !important;
- }
- }
- .uni-table-th,
- .uni-table-td {
- padding: px2rpx(16) px2rpx(5);
- color: var(--color-slate-800);
- box-sizing: border-box;
- }
- .expand-cell {
- padding: 0 !important;
- }
- }
- }
- .crm-chevron-down {
- transform: rotate(-90deg);
- cursor: pointer;
- }
- .mobile-table {
- :deep(.uni-table) {
- min-width: 0 !important;
- }
- }
- .detail-btn-mobile {
- background-color: #f0f0f0;
- color: #333;
- }
- /* 分页样式 */
- .pagination-container {
- margin: px2rpx(20) px2rpx(20);
- display: flex;
- align-items: center;
- justify-content: flex-end;
- gap: px2rpx(20);
- .pagination {
- display: flex;
- align-items: center;
- padding: px2rpx(10);
- }
- .page-item {
- display: flex;
- align-items: center;
- padding: 0 px2rpx(12);
- height: px2rpx(30);
- background-color: var(--color-white);
- border: 1px solid #dcdfe6;
- border-radius: px2rpx(8);
- font-size: px2rpx(16);
- color: #606266;
- cursor: pointer;
- transition: all 0.3s;
- margin: 0 px2rpx(6);
- }
- .page-item.prev {
- margin-right: px2rpx(10);
- }
- .page-item.next {
- margin-left: px2rpx(10);
- }
- .page-item:not(.disabled):hover {
- color: #007aff;
- border-color: #007aff;
- }
- .page-item.disabled {
- opacity: 0.5;
- cursor: not-allowed;
- pointer-events: none;
- }
- .page-numbers {
- display: flex;
- gap: px2rpx(8);
- }
- .page-number {
- display: flex;
- align-items: center;
- justify-content: center;
- min-width: px2rpx(40);
- height: px2rpx(30);
- padding: 0 px2rpx(4);
- background-color: var(--color-white);
- border-radius: px2rpx(8);
- font-size: px2rpx(16);
- color: #606266;
- cursor: pointer;
- transition: all 0.3s;
- }
- .page-number:hover {
- color: #007aff;
- border-color: #007aff;
- }
- .page-number.active {
- background-color: #007aff;
- border-color: #007aff;
- color: #fff;
- }
- .pagination-info {
- display: flex;
- align-items: center;
- gap: px2rpx(30);
- font-size: px2rpx(16);
- color: #909399;
- }
- .page-size-select {
- display: flex;
- align-items: center;
- gap: px2rpx(10);
- }
- .page-size-value {
- padding: px2rpx(6) px2rpx(20);
- border: 1px solid #dcdfe6;
- border-radius: px2rpx(8);
- color: #606266;
- }
- }
- @media screen and (max-width: 768px) {
- .pagination {
- flex-wrap: wrap;
- justify-content: center;
- }
- .page-item {
- padding: 0 px2rpx(16);
- }
- .page-number {
- min-width: px2rpx(60);
- }
- .pagination-info {
- flex-direction: column;
- gap: px2rpx(10);
- }
- }
- </style>
|