a
This commit is contained in:
162
src/components/TableColumnControl/README.md
Normal file
162
src/components/TableColumnControl/README.md
Normal file
@@ -0,0 +1,162 @@
|
||||
# TableColumnControl 表格列显隐控制组件
|
||||
|
||||
一个通用的表格列显示/隐藏控制组件,支持动态控制表格列的显示状态。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- ✅ 动态控制表格列的显示/隐藏
|
||||
- ✅ 支持全选/全不选
|
||||
- ✅ 支持重置为默认值
|
||||
- ✅ 支持 localStorage 持久化
|
||||
- ✅ 支持固定列(不可隐藏)
|
||||
- ✅ 支持始终显示的列
|
||||
- ✅ 可自定义触发按钮样式
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 基础用法
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div>
|
||||
<!-- 表格列控制按钮 -->
|
||||
<TableColumnControl
|
||||
:columns="tableColumns"
|
||||
v-model="visibleColumns"
|
||||
@change="handleColumnChange"
|
||||
/>
|
||||
|
||||
<!-- 表格 -->
|
||||
<el-table :data="tableData">
|
||||
<el-table-column
|
||||
v-for="col in visibleTableColumns"
|
||||
:key="col.prop"
|
||||
:prop="col.prop"
|
||||
:label="col.label"
|
||||
:width="col.width"
|
||||
/>
|
||||
</el-table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed } from 'vue'
|
||||
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
|
||||
|
||||
const tableColumns = [
|
||||
{ prop: 'name', label: '姓名', width: 120 },
|
||||
{ prop: 'age', label: '年龄', width: 80 },
|
||||
{ prop: 'email', label: '邮箱', width: 200 },
|
||||
{ prop: 'address', label: '地址', width: 300 }
|
||||
]
|
||||
|
||||
const visibleColumns = ref<string[]>(['name', 'age', 'email', 'address'])
|
||||
|
||||
// 根据 visibleColumns 过滤出需要显示的列
|
||||
const visibleTableColumns = computed(() => {
|
||||
return tableColumns.filter(col =>
|
||||
visibleColumns.value.includes(col.prop || col.label)
|
||||
)
|
||||
})
|
||||
|
||||
const handleColumnChange = (columns: string[]) => {
|
||||
console.log('显示的列:', columns)
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
### 使用 localStorage 持久化
|
||||
|
||||
```vue
|
||||
<TableColumnControl
|
||||
:columns="tableColumns"
|
||||
v-model="visibleColumns"
|
||||
storage-key="my-table-columns"
|
||||
/>
|
||||
```
|
||||
|
||||
### 固定列(不可隐藏)
|
||||
|
||||
```vue
|
||||
const tableColumns = [
|
||||
{ prop: 'name', label: '姓名', fixed: 'left' }, // 固定左侧,不可隐藏
|
||||
{ prop: 'age', label: '年龄' },
|
||||
{ prop: 'action', label: '操作', fixed: 'right' } // 固定右侧,不可隐藏
|
||||
]
|
||||
```
|
||||
|
||||
### 始终显示的列
|
||||
|
||||
```vue
|
||||
const tableColumns = [
|
||||
{ prop: 'name', label: '姓名', alwaysShow: true }, // 始终显示,不可隐藏
|
||||
{ prop: 'age', label: '年龄' }
|
||||
]
|
||||
```
|
||||
|
||||
### 自定义触发按钮
|
||||
|
||||
```vue
|
||||
<!-- 使用图标按钮 -->
|
||||
<TableColumnControl
|
||||
:columns="tableColumns"
|
||||
v-model="visibleColumns"
|
||||
trigger-type="default"
|
||||
trigger-circle
|
||||
/>
|
||||
|
||||
<!-- 使用文字按钮 -->
|
||||
<TableColumnControl
|
||||
:columns="tableColumns"
|
||||
v-model="visibleColumns"
|
||||
trigger-text="列设置"
|
||||
trigger-type="primary"
|
||||
/>
|
||||
|
||||
<!-- 使用链接按钮 -->
|
||||
<TableColumnControl
|
||||
:columns="tableColumns"
|
||||
v-model="visibleColumns"
|
||||
trigger-link
|
||||
trigger-text="自定义列"
|
||||
/>
|
||||
```
|
||||
|
||||
## Props
|
||||
|
||||
| 参数 | 说明 | 类型 | 默认值 |
|
||||
|------|------|------|--------|
|
||||
| columns | 表格列配置数组 | Column[] | 必填 |
|
||||
| modelValue | 当前显示的列的 prop 或 label 数组 | string[] | - |
|
||||
| storageKey | localStorage 存储的 key,用于持久化 | string | - |
|
||||
| triggerType | 触发按钮的类型 | 'default' \| 'primary' \| 'success' \| 'warning' \| 'danger' \| 'info' \| 'text' | 'default' |
|
||||
| triggerSize | 触发按钮的大小 | 'large' \| 'default' \| 'small' | 'default' |
|
||||
| triggerCircle | 触发按钮是否为圆形 | boolean | false |
|
||||
| triggerText | 触发按钮的文字 | string | '' |
|
||||
| triggerLink | 触发按钮是否为链接样式 | boolean | false |
|
||||
|
||||
## Events
|
||||
|
||||
| 事件名 | 说明 | 回调参数 |
|
||||
|--------|------|----------|
|
||||
| update:modelValue | 显示的列变化时触发 | (columns: string[]) |
|
||||
| change | 显示的列变化时触发 | (columns: string[]) |
|
||||
|
||||
## Column 接口
|
||||
|
||||
```typescript
|
||||
interface Column {
|
||||
prop?: string // 列的 prop,用于标识列
|
||||
label: string // 列的标签
|
||||
fixed?: boolean | 'left' | 'right' // 固定列,不可隐藏
|
||||
alwaysShow?: boolean // 始终显示的列,不可隐藏
|
||||
[key: string]: any // 其他属性
|
||||
}
|
||||
```
|
||||
|
||||
## 插槽
|
||||
|
||||
| 插槽名 | 说明 |
|
||||
|--------|------|
|
||||
| trigger | 自定义触发按钮内容 |
|
||||
|
||||
196
src/components/TableColumnControl/USAGE.md
Normal file
196
src/components/TableColumnControl/USAGE.md
Normal file
@@ -0,0 +1,196 @@
|
||||
# TableColumnControl 使用指南
|
||||
|
||||
## 两种使用方式
|
||||
|
||||
### 方式一:自动提取(推荐)✨
|
||||
|
||||
自动从 `el-table` 中提取列配置,无需手动配置。
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div>
|
||||
<!-- 列设置按钮 -->
|
||||
<TableColumnControl
|
||||
:table-ref="tableRef"
|
||||
v-model="visibleTableColumns"
|
||||
storage-key="my-table-columns"
|
||||
trigger-text="列设置"
|
||||
:auto-extract-options="{
|
||||
alwaysShow: ['name', 'action'], // 始终显示的列(prop 或 label)
|
||||
defaultHidden: ['remark'], // 默认隐藏的列
|
||||
}"
|
||||
/>
|
||||
|
||||
<!-- 表格 -->
|
||||
<el-table ref="tableRef" :data="tableData">
|
||||
<el-table-column prop="name" label="姓名" width="120" />
|
||||
<el-table-column prop="age" label="年龄" width="80" />
|
||||
<el-table-column prop="email" label="邮箱" width="200" />
|
||||
<el-table-column prop="remark" label="备注" width="300" />
|
||||
<el-table-column label="操作" width="150" fixed="right">
|
||||
<template #default="scope">
|
||||
<el-button @click="handleEdit(scope.row)">编辑</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
|
||||
import type { TableInstance } from 'element-plus'
|
||||
|
||||
const tableRef = ref<TableInstance>()
|
||||
const visibleTableColumns = ref<string[]>([])
|
||||
const tableData = ref([...])
|
||||
</script>
|
||||
```
|
||||
|
||||
**优点:**
|
||||
- ✅ 无需手动配置列信息
|
||||
- ✅ 自动同步表格列的变化
|
||||
- ✅ 代码更简洁
|
||||
|
||||
### 方式二:手动配置
|
||||
|
||||
手动传入列配置,适合需要自定义列信息的场景。
|
||||
|
||||
```vue
|
||||
<template>
|
||||
<div>
|
||||
<!-- 列设置按钮 -->
|
||||
<TableColumnControl
|
||||
:columns="tableColumnConfig"
|
||||
v-model="visibleTableColumns"
|
||||
storage-key="my-table-columns"
|
||||
trigger-text="列设置"
|
||||
/>
|
||||
|
||||
<!-- 表格 -->
|
||||
<el-table :data="tableData">
|
||||
<el-table-column
|
||||
v-if="isColumnVisible('name')"
|
||||
prop="name"
|
||||
label="姓名"
|
||||
width="120"
|
||||
/>
|
||||
<el-table-column
|
||||
v-if="isColumnVisible('age')"
|
||||
prop="age"
|
||||
label="年龄"
|
||||
width="80"
|
||||
/>
|
||||
<!-- ... 其他列 ... -->
|
||||
</el-table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed } from 'vue'
|
||||
import TableColumnControl from '/@/components/TableColumnControl/index.vue'
|
||||
|
||||
const tableColumnConfig = [
|
||||
{ prop: 'name', label: '姓名', width: 120 },
|
||||
{ prop: 'age', label: '年龄', width: 80 },
|
||||
{ prop: 'email', label: '邮箱', width: 200 },
|
||||
{ prop: 'action', label: '操作', width: 150, fixed: 'right', alwaysShow: true }
|
||||
]
|
||||
|
||||
const visibleTableColumns = ref<string[]>([])
|
||||
const tableData = ref([...])
|
||||
|
||||
// 判断列是否显示
|
||||
const isColumnVisible = (propOrLabel: string) => {
|
||||
const column = tableColumnConfig.find(col => (col.prop || col.label) === propOrLabel)
|
||||
if (column && (column.fixed !== undefined || column.alwaysShow)) {
|
||||
return true
|
||||
}
|
||||
return visibleTableColumns.value.includes(propOrLabel)
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
## 自动提取的配置选项
|
||||
|
||||
```typescript
|
||||
interface AutoExtractOptions {
|
||||
// 默认隐藏的列(prop 或 label)
|
||||
defaultHidden?: string[]
|
||||
|
||||
// 始终显示的列(prop 或 label)
|
||||
alwaysShow?: string[]
|
||||
|
||||
// 列配置映射(用于自定义列的显示名称等)
|
||||
columnMap?: Record<string, Partial<ColumnConfig>>
|
||||
}
|
||||
```
|
||||
|
||||
### 示例
|
||||
|
||||
```vue
|
||||
<TableColumnControl
|
||||
:table-ref="tableRef"
|
||||
v-model="visibleTableColumns"
|
||||
storage-key="my-table-columns"
|
||||
:auto-extract-options="{
|
||||
// 默认隐藏备注列
|
||||
defaultHidden: ['remark', 'description'],
|
||||
|
||||
// 始终显示姓名和操作列
|
||||
alwaysShow: ['name', 'action'],
|
||||
|
||||
// 自定义列的显示名称
|
||||
columnMap: {
|
||||
'email': { label: '电子邮箱' },
|
||||
'phone': { label: '联系电话' }
|
||||
}
|
||||
}"
|
||||
/>
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **自动提取的限制**:
|
||||
- 需要在表格渲染完成后才能提取列配置
|
||||
- 如果表格列是动态生成的,可能需要调用 `refreshColumns()` 方法
|
||||
|
||||
2. **固定列**:
|
||||
- 使用 `fixed="left"` 或 `fixed="right"` 的列会自动标记为不可隐藏
|
||||
- 在 `alwaysShow` 中指定的列也会不可隐藏
|
||||
|
||||
3. **存储键(storageKey)**:
|
||||
- 建议为每个页面使用唯一的 `storageKey`,避免列配置冲突
|
||||
- 格式建议:`页面名称-table-columns`,如 `user-list-table-columns`
|
||||
|
||||
4. **性能考虑**:
|
||||
- 自动提取会在组件挂载和表格更新时执行
|
||||
- 对于大型表格,建议使用手动配置以获得更好的性能
|
||||
|
||||
## 迁移指南
|
||||
|
||||
从手动配置迁移到自动提取:
|
||||
|
||||
**之前(手动配置):**
|
||||
```vue
|
||||
<TableColumnControl
|
||||
:columns="tableColumnConfig"
|
||||
v-model="visibleTableColumns"
|
||||
storage-key="my-table-columns"
|
||||
/>
|
||||
```
|
||||
|
||||
**之后(自动提取):**
|
||||
```vue
|
||||
<TableColumnControl
|
||||
:table-ref="tableRef"
|
||||
v-model="visibleTableColumns"
|
||||
storage-key="my-table-columns"
|
||||
/>
|
||||
```
|
||||
|
||||
只需要:
|
||||
1. 将 `:columns` 改为 `:table-ref="tableRef"`
|
||||
2. 在 `el-table` 上添加 `ref="tableRef"`
|
||||
3. 移除 `tableColumnConfig` 和 `isColumnVisible` 函数(如果不再需要)
|
||||
|
||||
461
src/components/TableColumnControl/index.vue
Normal file
461
src/components/TableColumnControl/index.vue
Normal file
@@ -0,0 +1,461 @@
|
||||
<template>
|
||||
<div class="table-column-control">
|
||||
<el-button
|
||||
:type="triggerType"
|
||||
:icon="Setting"
|
||||
:size="triggerSize"
|
||||
:circle="triggerCircle"
|
||||
:link="triggerLink"
|
||||
@click="visible = true"
|
||||
>
|
||||
<slot name="trigger">
|
||||
{{ triggerText || '列设置' }}
|
||||
</slot>
|
||||
</el-button>
|
||||
|
||||
<el-dialog
|
||||
v-model="visible"
|
||||
title="列显示设置"
|
||||
:width="dialogWidth"
|
||||
append-to-body
|
||||
>
|
||||
<div class="column-control-content">
|
||||
<div class="column-control-header">
|
||||
<div class="header-actions">
|
||||
<el-button
|
||||
type="primary"
|
||||
link
|
||||
@click="handleToggleSelectAll"
|
||||
>
|
||||
{{ isAllSelected ? '取消全选' : '全选' }}
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="column-control-body">
|
||||
<el-checkbox-group v-model="checkedColumns" @change="handleColumnChange" class="column-checkbox-group">
|
||||
<div
|
||||
v-for="column in actualColumns"
|
||||
:key="column.prop || column.label"
|
||||
class="column-item"
|
||||
>
|
||||
<el-checkbox
|
||||
:label="column.prop || column.label"
|
||||
:disabled="column.fixed !== undefined || column.alwaysShow"
|
||||
>
|
||||
{{ column.label }}
|
||||
</el-checkbox>
|
||||
<el-tag v-if="column.fixed !== undefined" size="small" type="info">
|
||||
{{ column.fixed === 'left' ? '固定左侧' : column.fixed === 'right' ? '固定右侧' : '固定' }}
|
||||
</el-tag>
|
||||
</div>
|
||||
</el-checkbox-group>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<div class="column-control-footer">
|
||||
<el-button @click="handleReset">重置</el-button>
|
||||
<el-button type="primary" @click="handleConfirm">确定</el-button>
|
||||
</div>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch, onMounted, nextTick, type Ref } from 'vue'
|
||||
import { Setting } from '@element-plus/icons-vue'
|
||||
import type { TableInstance } from 'element-plus'
|
||||
import { useTableColumns, type ColumnConfig } from '/@/composables/useTableColumns'
|
||||
|
||||
interface Column {
|
||||
prop?: string
|
||||
label: string
|
||||
fixed?: boolean | 'left' | 'right'
|
||||
alwaysShow?: boolean // 始终显示的列,不可隐藏
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
interface Props {
|
||||
columns?: Column[] // 手动配置的列(可选,如果提供了 tableRef 则自动提取)
|
||||
tableRef?: Ref<TableInstance | undefined> // el-table 的 ref,用于自动提取列配置
|
||||
modelValue?: string[] // 当前显示的列
|
||||
storageKey?: string // localStorage 存储的 key,用于持久化
|
||||
triggerType?: 'default' | 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'text'
|
||||
triggerSize?: 'large' | 'default' | 'small'
|
||||
triggerCircle?: boolean
|
||||
triggerText?: string
|
||||
triggerLink?: boolean
|
||||
dialogWidth?: string // 对话框宽度
|
||||
// 自动提取时的配置选项
|
||||
autoExtractOptions?: {
|
||||
defaultHidden?: string[]
|
||||
alwaysShow?: string[]
|
||||
columnMap?: Record<string, Partial<ColumnConfig>>
|
||||
}
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
triggerType: 'default',
|
||||
triggerSize: 'default',
|
||||
triggerCircle: false,
|
||||
triggerText: '',
|
||||
triggerLink: false,
|
||||
dialogWidth: '600px'
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: string[]]
|
||||
'change': [value: string[]]
|
||||
}>()
|
||||
|
||||
const visible = ref(false)
|
||||
const checkedColumns = ref<string[]>([])
|
||||
|
||||
// 监听弹窗打开,触发列配置重新提取
|
||||
watch(visible, (newVal) => {
|
||||
console.log('[TableColumnControl] 弹窗状态变化:', newVal)
|
||||
if (newVal && props.tableRef) {
|
||||
console.log('[TableColumnControl] 弹窗打开,tableRef 存在:', props.tableRef)
|
||||
console.log('[TableColumnControl] tableRef.value:', props.tableRef.value)
|
||||
console.log('[TableColumnControl] tableRef.value 类型:', typeof props.tableRef.value)
|
||||
|
||||
// 尝试多种方式获取表格实例
|
||||
const getTableInstance = (): TableInstance | null => {
|
||||
// 方法1: 直接从 props.tableRef.value 获取
|
||||
if (props.tableRef?.value) {
|
||||
console.log('[TableColumnControl] 从 props.tableRef.value 获取表格实例')
|
||||
return props.tableRef.value
|
||||
}
|
||||
|
||||
// 方法2: 尝试从 props.tableRef 本身获取(可能是直接的 ref 对象)
|
||||
if ((props.tableRef as any).value) {
|
||||
console.log('[TableColumnControl] 从 props.tableRef 的 value 属性获取表格实例')
|
||||
return (props.tableRef as any).value
|
||||
}
|
||||
|
||||
// 方法3: 如果 props.tableRef 本身就是表格实例(不应该发生,但作为备用)
|
||||
if ((props.tableRef as any).$el) {
|
||||
console.log('[TableColumnControl] props.tableRef 本身就是表格实例')
|
||||
return props.tableRef as any
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
// 如果 tableRef.value 已经有值,直接提取
|
||||
const tableInstance = getTableInstance()
|
||||
if (tableInstance) {
|
||||
const tableEl = (tableInstance as any).$el
|
||||
if (tableEl) {
|
||||
console.log('[TableColumnControl] 表格实例已就绪,立即提取列配置')
|
||||
nextTick(() => {
|
||||
refreshAutoColumns()
|
||||
console.log('[TableColumnControl] 刷新后列数:', actualColumns.value.length)
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 等待 tableRef.value 有值后再提取
|
||||
let waitCount = 0
|
||||
const maxWaitCount = 50 // 最多等待 5 秒(50 * 100ms)
|
||||
let waitTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
const waitForTableRef = () => {
|
||||
// 尝试获取表格实例
|
||||
const tableInstance = getTableInstance()
|
||||
if (tableInstance) {
|
||||
const tableEl = (tableInstance as any).$el
|
||||
if (tableEl) {
|
||||
console.log('[TableColumnControl] 表格实例已就绪,开始提取列配置')
|
||||
nextTick(() => {
|
||||
refreshAutoColumns()
|
||||
console.log('[TableColumnControl] 刷新后列数:', actualColumns.value.length)
|
||||
|
||||
// 如果还是没有数据,多次重试
|
||||
let retryCount = 0
|
||||
const maxRetries = 10
|
||||
const retryInterval = setInterval(() => {
|
||||
retryCount++
|
||||
console.log(`[TableColumnControl] 第 ${retryCount} 次重试刷新列配置`)
|
||||
refreshAutoColumns()
|
||||
console.log(`[TableColumnControl] 重试后列数:`, actualColumns.value.length)
|
||||
if (actualColumns.value.length > 0 || retryCount >= maxRetries) {
|
||||
console.log('[TableColumnControl] 停止重试,最终列数:', actualColumns.value.length)
|
||||
clearInterval(retryInterval)
|
||||
}
|
||||
}, 200)
|
||||
})
|
||||
return // 成功获取,退出
|
||||
}
|
||||
}
|
||||
|
||||
// 继续等待
|
||||
waitCount++
|
||||
if (waitCount < maxWaitCount) {
|
||||
console.log(`[TableColumnControl] tableRef.value 还未就绪,等待中... (${waitCount}/${maxWaitCount})`)
|
||||
waitTimer = setTimeout(waitForTableRef, 100)
|
||||
} else {
|
||||
console.warn('[TableColumnControl] 等待超时,tableRef.value 仍未就绪')
|
||||
console.warn('[TableColumnControl] props.tableRef:', props.tableRef)
|
||||
console.warn('[TableColumnControl] props.tableRef?.value:', props.tableRef?.value)
|
||||
// 即使超时,也尝试提取一次(可能表格已经渲染了,只是 ref 没有正确绑定)
|
||||
console.log('[TableColumnControl] 尝试强制提取列配置')
|
||||
refreshAutoColumns()
|
||||
console.log('[TableColumnControl] 强制提取后列数:', actualColumns.value.length)
|
||||
}
|
||||
}
|
||||
|
||||
// 延迟一下,确保表格已渲染
|
||||
setTimeout(() => {
|
||||
waitForTableRef()
|
||||
}, 300)
|
||||
|
||||
// 清理函数:弹窗关闭时清除等待定时器
|
||||
return () => {
|
||||
if (waitTimer) {
|
||||
clearTimeout(waitTimer)
|
||||
waitTimer = null
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.warn('[TableColumnControl] 弹窗打开但 tableRef 不存在或为空')
|
||||
}
|
||||
})
|
||||
|
||||
// 如果提供了 tableRef,使用自动提取;否则使用手动配置的 columns
|
||||
const tableColumnsResult = props.tableRef
|
||||
? useTableColumns(props.tableRef, props.storageKey, props.autoExtractOptions)
|
||||
: {
|
||||
columns: computed(() => []),
|
||||
visibleColumns: computed(() => []),
|
||||
updateVisibleColumns: () => {},
|
||||
refreshColumns: () => {},
|
||||
isColumnVisible: () => true
|
||||
}
|
||||
|
||||
const {
|
||||
columns: autoColumns,
|
||||
visibleColumns: autoVisibleColumns,
|
||||
updateVisibleColumns: updateAutoVisibleColumns,
|
||||
refreshColumns: refreshAutoColumns,
|
||||
isColumnVisible: autoIsColumnVisible
|
||||
} = tableColumnsResult
|
||||
|
||||
// 监听 tableRef.value 的变化,当它被赋值时触发列配置提取
|
||||
if (props.tableRef) {
|
||||
// 尝试多种方式监听 tableRef.value 的变化
|
||||
watch(() => {
|
||||
// 尝试多种方式获取 tableRef.value
|
||||
if (props.tableRef?.value) {
|
||||
return props.tableRef.value
|
||||
}
|
||||
if ((props.tableRef as any).value) {
|
||||
return (props.tableRef as any).value
|
||||
}
|
||||
return null
|
||||
}, (newVal, oldVal) => {
|
||||
if (newVal && newVal !== oldVal) {
|
||||
console.log('[TableColumnControl] tableRef.value 已赋值,触发列配置提取')
|
||||
// 延迟一下,确保表格完全渲染
|
||||
setTimeout(() => {
|
||||
nextTick(() => {
|
||||
refreshAutoColumns()
|
||||
console.log('[TableColumnControl] 列配置提取完成,列数:', actualColumns.value.length)
|
||||
})
|
||||
}, 200)
|
||||
}
|
||||
}, { immediate: true }) // 立即检查一次,如果 tableRef.value 已经有值,立即触发
|
||||
}
|
||||
|
||||
// 调试:检查 tableRef 传递
|
||||
console.log('[TableColumnControl] props.tableRef:', props.tableRef)
|
||||
console.log('[TableColumnControl] props.tableRef?.value:', props.tableRef?.value)
|
||||
|
||||
// 暴露给父组件使用
|
||||
defineExpose({
|
||||
isColumnVisible: autoIsColumnVisible,
|
||||
visibleColumns: autoVisibleColumns,
|
||||
refreshColumns: refreshAutoColumns
|
||||
})
|
||||
|
||||
// 实际使用的列配置
|
||||
const actualColumns = computed(() => {
|
||||
const result = props.tableRef && autoColumns.value.length > 0
|
||||
? autoColumns.value
|
||||
: props.columns || []
|
||||
console.log('[TableColumnControl] actualColumns 计算:', {
|
||||
hasTableRef: !!props.tableRef,
|
||||
autoColumnsLength: autoColumns.value.length,
|
||||
propsColumnsLength: props.columns?.length || 0,
|
||||
resultLength: result.length
|
||||
})
|
||||
return result
|
||||
})
|
||||
|
||||
// 初始化选中的列
|
||||
const initCheckedColumns = () => {
|
||||
if (props.modelValue && props.modelValue.length > 0) {
|
||||
checkedColumns.value = [...props.modelValue]
|
||||
} else if (props.tableRef && autoVisibleColumns.value.length > 0) {
|
||||
// 使用自动提取的可见列
|
||||
checkedColumns.value = [...autoVisibleColumns.value]
|
||||
} else if (props.storageKey) {
|
||||
// 从 localStorage 读取
|
||||
const saved = localStorage.getItem(props.storageKey)
|
||||
if (saved) {
|
||||
try {
|
||||
checkedColumns.value = JSON.parse(saved)
|
||||
} catch (e) {
|
||||
// 如果解析失败,使用默认值(所有列)
|
||||
checkedColumns.value = getDefaultColumns()
|
||||
}
|
||||
} else {
|
||||
checkedColumns.value = getDefaultColumns()
|
||||
}
|
||||
} else {
|
||||
checkedColumns.value = getDefaultColumns()
|
||||
}
|
||||
}
|
||||
|
||||
// 获取默认显示的列(所有可隐藏的列)
|
||||
const getDefaultColumns = (): string[] => {
|
||||
return actualColumns.value
|
||||
.filter(col => !col.alwaysShow && col.fixed === undefined)
|
||||
.map(col => col.prop || col.label)
|
||||
}
|
||||
|
||||
// 获取所有可选择的列
|
||||
const selectableColumns = computed(() => {
|
||||
return actualColumns.value
|
||||
.filter(col => !col.alwaysShow && col.fixed === undefined)
|
||||
.map(col => col.prop || col.label)
|
||||
})
|
||||
|
||||
// 判断是否全选
|
||||
const isAllSelected = computed(() => {
|
||||
const selectable = selectableColumns.value
|
||||
if (selectable.length === 0) return false
|
||||
return selectable.every(col => checkedColumns.value.includes(col))
|
||||
})
|
||||
|
||||
// 切换全选/全不选
|
||||
const handleToggleSelectAll = () => {
|
||||
if (isAllSelected.value) {
|
||||
// 当前全选,执行全不选
|
||||
checkedColumns.value = []
|
||||
} else {
|
||||
// 当前未全选,执行全选
|
||||
checkedColumns.value = [...selectableColumns.value]
|
||||
}
|
||||
}
|
||||
|
||||
// 重置为默认值
|
||||
const handleReset = () => {
|
||||
checkedColumns.value = getDefaultColumns()
|
||||
handleColumnChange(checkedColumns.value)
|
||||
}
|
||||
|
||||
// 确认
|
||||
const handleConfirm = () => {
|
||||
handleColumnChange(checkedColumns.value)
|
||||
visible.value = false
|
||||
}
|
||||
|
||||
// 列变化处理
|
||||
const handleColumnChange = (value: string[]) => {
|
||||
emit('update:modelValue', value)
|
||||
emit('change', value)
|
||||
|
||||
// 如果使用自动提取,同步更新
|
||||
if (props.tableRef) {
|
||||
updateAutoVisibleColumns(value)
|
||||
} else {
|
||||
// 保存到 localStorage
|
||||
if (props.storageKey) {
|
||||
localStorage.setItem(props.storageKey, JSON.stringify(value))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 监听外部 modelValue 变化
|
||||
watch(() => props.modelValue, (newVal) => {
|
||||
if (newVal && newVal.length > 0) {
|
||||
checkedColumns.value = [...newVal]
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
// 初始化
|
||||
onMounted(() => {
|
||||
initCheckedColumns()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.table-column-control {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.column-control-content {
|
||||
.column-control-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding-bottom: 12px;
|
||||
margin-bottom: 12px;
|
||||
border-bottom: 1px solid #ebeef5;
|
||||
|
||||
.header-title {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #303133;
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.column-control-body {
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
margin-bottom: 12px;
|
||||
|
||||
.column-checkbox-group {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px 16px;
|
||||
}
|
||||
|
||||
.column-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 120px;
|
||||
|
||||
:deep(.el-checkbox) {
|
||||
margin-right: 0;
|
||||
|
||||
.el-checkbox__label {
|
||||
font-size: 14px;
|
||||
color: #606266;
|
||||
padding-left: 8px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.column-control-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
padding-top: 12px;
|
||||
border-top: 1px solid #ebeef5;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user