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);
|
});
|
}
|