wujianwei
2025-09-10 c0f6fb84a98db212b0780f44430d4e0cdf1b0302
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { ref, onMounted, onBeforeUnmount } from 'vue';
 
export function useTableColumnWidth(defaultOption: any, tableRef: any) {
    const columns = Object.keys(defaultOption.column).map(key => ({
        ...defaultOption.column[key],
        prop: key,
    }));
    if ( defaultOption.selection != false){
        columns.unshift({prop: 'indexTh'})
    }
    if (defaultOption.menu != false){
        columns.push({prop: 'menuTh'})
    }
    // 获取页面 ID
    const pageId = defaultOption.pageKey;
 
    // 保存列宽
    const saveColumnWidths = () => {
        const columnWidths: { [key: string]: number } = {};
        const tableElement = tableRef.value.$el;
        const columnHeaders = tableElement.querySelectorAll('.el-table__header th');
        console.log(defaultOption.selection)
        columnHeaders.forEach((th: HTMLElement, index: number) => {
            const column = columns[index];
            columnWidths[column.prop] = th.offsetWidth;
        });
 
        // 使用按页面 ID 分片存储列宽
        localStorage.setItem(`columnWidths_${pageId}`, JSON.stringify(columnWidths));
    };
 
    // 加载列宽
    const loadColumnWidths = () => {
        const savedWidths = localStorage.getItem(`columnWidths_${pageId}`);
        if (savedWidths) {
            const columnWidths = JSON.parse(savedWidths);
            applyColumnWidths(columnWidths);
        }
    };
 
    // 应用列宽到表格
    const applyColumnWidths = (columnWidths: { [key: string]: number }) => {
        Object.keys(columnWidths).forEach((key: string) => {
            let columnElement = defaultOption.column[key];
            if (columnElement) {
                defaultOption.column[key].width = columnWidths[key];
            }
            if (key === 'menuTh'){
                defaultOption.menuWidth = columnWidths[key];
            }
            if (key === 'indexTh'){
                defaultOption.indexWidth = columnWidths[key];
            }
        })
    };
 
    // 在组件挂载时加载列宽
    onMounted(() => {
        loadColumnWidths();
        window.addEventListener('beforeunload', saveColumnWidths); // 监听页面离开
    });
 
    // 在组件销毁时保存列宽
    onBeforeUnmount(() => {
        saveColumnWidths();
        window.removeEventListener('beforeunload', saveColumnWidths);
    });
}