| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849 |
- <template>
- <view class="table-container">
- <!-- 表格 -->
- <uni-table :type="selectionType" :border="false" @selection-change="handleSelectionChange">
- <uni-tr class="tabel-header">
- <uni-th v-for="column in columns" :key="column.prop" :align="column.align || 'center'"
- :width="column.width || '50'" :class="[
- headerClass
- ]" :style="getHeaderStyle(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-th v-if="showOperation" align="center" :width="operationWidth" :style="getOperationHeaderStyle()">
- {{ t('common.operation') }}
- </uni-th>
- </uni-tr>
- <template v-for="(row, rowIndex) in tableData" :key="rowIndex">
- <uni-tr>
- <uni-td v-for="column in columns" :key="column.prop" :align="column.align || 'center'"
- :class="getCellClass(column, row)" :style="getCellStyle(column, row)">
- <!-- 自定义渲染插槽 -->
- <slot v-if="column.slot" :name="column.slot" :row="row" :column="column" :index="rowIndex">
- {{ row[column.prop] }}
- </slot>
- <!-- 标签类型渲染 -->
- <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>
- <!-- 默认文本渲染 -->
- <template v-else>{{ formatCellValue(row[column.prop], column, row) }}</template>
- </uni-td>
- <!-- 操作按钮 -->
- <uni-td v-if="showOperation" align="center">
- <view class="operation-btns">
- <template v-for="(action, index) in operationActions" :key="index">
- <button v-if="showAction(action, row)" class="btn" size="mini"
- :type="action.type || 'default'" @click="handleAction(action, row)">
- <cwg-icon :name="action.icon" :size="16" color="#fff" v-if="action.icon" />
- {{ action.text }}
- </button>
- </template>
- </view>
- </uni-td>
- </uni-tr>
- <!-- 展开行 - 这里是您要放置 expand 插槽的地方 -->
- <uni-tr v-if="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-tr v-if="tableData.length === 0">
- <uni-td :colspan="columnSpan" align="center">
- <view class="empty-data">
- <uni-icons type="info" size="30" color="#999"></uni-icons>
- <text class="empty-text">暂无数据</text>
- </view>
- </uni-td>
- </uni-tr>
- </uni-table>
- <!-- 分页组件 -->
- <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"></uni-icons>
- <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"></uni-icons>
- </view>
- </view>
- </view>
- </view>
- </template>
- <script setup>
- import { ref, computed, watch, onMounted } from 'vue'
- const props = defineProps({
- // 表格列配置
- columns: {
- type: Array,
- required: true,
- default: () => []
- },
- // API 请求函数
- api: {
- type: Function,
- required: true
- },
- // 查询参数
- queryParams: {
- type: Object,
- default: () => ({})
- },
- // 是否立即加载
- immediate: {
- type: Boolean,
- default: true
- },
- // 选择类型:'selection' | null
- selectionType: {
- type: String,
- default: null
- },
- // 是否显示操作列
- showOperation: {
- type: Boolean,
- default: false
- },
- // 操作按钮配置
- operationActions: {
- type: Array,
- default: () => [
- { text: '编辑', type: 'primary', action: 'edit', icon: 'crm-puls' },
- { text: '删除', type: 'warn', action: 'delete', icon: 'crm-delete' },
- { text: '查看', type: 'default', action: 'view', icon: 'view' }
- ]
- },
- // 是否显示底部操作栏
- showBottomActions: {
- type: Boolean,
- default: false
- },
- // 底部操作按钮
- bottomActions: {
- type: Array,
- default: () => []
- },
- // 是否显示每页条数选择
- showPageSize: {
- type: Boolean,
- default: true
- },
- // 是否显示分页
- showPagination: {
- type: Boolean,
- default: true
- },
- // 每页条数选项
- pageSizes: {
- type: Array,
- default: () => [10, 20, 30, 50, 100]
- },
- // 默认每页条数
- defaultPageSize: {
- type: Number,
- default: 10
- },
- // ========== 表头样式自定义 ==========
- // 表头背景色
- headerBackground: {
- type: String,
- default: 'var(--color-slate-200)'
- },
- // 表头文字颜色
- 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'
- }
- })
- const emit = defineEmits([
- 'selection-change',
- 'action-click',
- 'bottom-action-click',
- 'page-change',
- 'load-success',
- 'load-error'
- ])
- // 展开行状态
- const expandedRows = ref({})
- // 切换行展开状态
- 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 tableData = ref([])
- const selectedItems = ref([])
- // 分页参数
- const pagination = ref({
- current: 1,
- pageSize: props.defaultPageSize,
- total: 0,
- pages: 0
- })
- // 加载状态
- const loading = ref(false)
- // 计算列跨度
- const columnSpan = computed(() => {
- let span = props.columns.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)
- })
- // 监听查询参数变化
- watch(() => props.queryParams, () => {
- refreshTable()
- }, { deep: true })
- // ========== 表头样式计算 ==========
- // 获取表头样式
- 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.headerStyle) {
- Object.assign(baseStyle, column.headerStyle)
- }
- return baseStyle
- }
- // 获取操作列表头样式
- const getOperationHeaderStyle = () => {
- return {
- backgroundColor: props.headerBackground,
- color: props.headerColor,
- fontSize: typeof props.headerFontSize === 'number' ? props.headerFontSize + 'px' : props.headerFontSize,
- fontWeight: props.headerFontWeight,
- height: typeof props.headerHeight === 'number' ? props.headerHeight + 'px' : props.headerHeight,
- lineHeight: typeof props.headerHeight === 'number' ? props.headerHeight + 'px' : props.headerHeight,
- position: props.stickyHeader ? 'sticky' : 'static',
- top: props.stickyHeader ? props.stickyOffset : 'auto',
- zIndex: props.stickyHeader ? 100 : 'auto'
- }
- }
- // 获取单元格样式
- const getCellStyle = (column, row) => {
- const style = {}
- 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 loadData = async () => {
- if (loading.value) return
- loading.value = true
- try {
- const params = {
- page: {
- current: pagination.value.current,
- size: pagination.value.pageSize
- },
- ...props.queryParams
- }
- const res = await props.api(params)
- // 处理不同的API返回格式
- if (res.code === 200 || res.code === 0) {
- const data = res.data || res
- // 支持不同的分页数据结构
- if (Array.isArray(data)) {
- tableData.value = data
- pagination.value.total = data.length
- pagination.value.pages = 1
- } else if (data.list || data.records) {
- tableData.value = data.list || data.records
- 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 handleAction = (action, row) => {
- emit('action-click', { action: action.action, row, original: action })
- }
- // 底部操作点击
- const handleBottomAction = (action) => {
- emit('bottom-action-click', action)
- }
- // 判断是否显示操作按钮
- const showAction = (action, row) => {
- if (action.show) {
- return action.show(row)
- }
- return true
- }
- // 格式化单元格值
- 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 handlePreviewImage = (url) => {
- uni.previewImage({
- urls: [url]
- })
- }
- // 获取选中项
- const getSelectedItems = () => {
- return selectedItems.value
- }
- // 清空选中
- const clearSelection = () => {
- selectedItems.value = []
- }
- // 暴露方法给父组件
- defineExpose({
- refreshTable,
- reload,
- getSelectedItems,
- clearSelection,
- loadData,
- tableData,
- toggleRowExpand,
- pagination
- })
- // 初始化加载
- onMounted(() => {
- if (props.immediate) {
- loadData()
- }
- })
- </script>
- <style scoped lang="scss">
- @import "@/uni.scss";
- .table-container {
- width: 100%;
- overflow-x: auto;
- /* 关键:横向滚动 */
- -webkit-overflow-scrolling: touch;
- /* 流畅滚动 */
- max-height: calc(100vh - 209px);
- overflow: hidden;
- 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;
- .uni-icons {
- transition: all 0.3s;
- }
- }
- }
- &.sortable {
- cursor: pointer;
- &:hover {
- .sort-icon .uni-icons {
- color: var(--color-primary) !important;
- }
- }
- }
- &::after {
- display: none;
- }
- }
- .uni-table-tr {
- border-bottom: 5px solid var(--color-slate-200) !important;
- &:last-child {
- border-bottom: none !important;
- }
- }
- .uni-table-th,
- .uni-table-td {
- padding: px2rpx(12) px2rpx(20);
- color: var(--color-slate-800);
- box-sizing: border-box;
- }
- .uni-table-td {
- word-break: break-word;
- }
- .expand-cell {
- padding: 0 !important;
- }
- }
- }
- .table-image {
- width: px2rpx(30);
- height: px2rpx(30);
- border-radius: px2rpx(8);
- }
- .operation-btns {
- display: flex;
- gap: px2rpx(10);
- justify-content: center;
- flex-wrap: wrap;
- }
- .btn {
- margin: 0 px2rpx(4);
- font-size: px2rpx(16);
- padding: 0 px2rpx(20);
- height: px2rpx(36);
- border-radius: none;
- display: flex;
- align-items: center;
- justify-content: center;
- cursor: pointer;
- transition: all 0.3s;
- &:hover {
- opacity: 0.8;
- }
- &:active {
- transform: scale(0.95);
- }
- }
- .empty-data {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: px2rpx(30) 0;
- }
- .empty-text {
- margin-top: px2rpx(20);
- font-size: px2rpx(16);
- color: #999;
- }
- .bottom-actions {
- margin: px2rpx(30) px2rpx(20);
- display: flex;
- justify-content: space-between;
- align-items: center;
- }
- .left-actions,
- .right-actions {
- display: flex;
- gap: px2rpx(20);
- }
- /* 分页样式 */
- .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>
|