Files
BMS/bms-front/src/utils/columnSettings.js
T
2026-09-22 09:53:03 +08:00

58 lines
1.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 表格列显隐偏好(localStorage 持久化)。
*
* @param {string} storageKey 存储键(页面级唯一,如 'customer-list')
* @param {Array<{key:string,label:string,fixed?:boolean,defaultVisible?:boolean}>} columns 列定义
* @returns {{colVisible: object, isColVisible: Function, resetColumns: Function}}
* colVisible 响应式显隐映射,模板中 v-if="isColVisible('xxx')"
* resetColumns 恢复默认(供列设置弹窗调用)
*/
const PREFIX = 'bms:columnSettings:'
export function useColumnSettings(storageKey, columns) {
const defaults = {}
columns.forEach(c => {
defaults[c.key] = c.defaultVisible !== false
})
let saved = {}
try {
saved = JSON.parse(localStorage.getItem(PREFIX + storageKey) || '{}') || {}
} catch (e) {
saved = {}
}
// 仅接受当前列定义中存在的 key(兼容历史存储与列增减)
const colVisible = reactive({ ...defaults })
columns.forEach(c => {
if (Object.prototype.hasOwnProperty.call(saved, c.key)) {
colVisible[c.key] = !!saved[c.key]
}
// 固定列强制可见
if (c.fixed) colVisible[c.key] = true
})
watch(colVisible, val => {
localStorage.setItem(PREFIX + storageKey, JSON.stringify(val))
}, { deep: true })
function isColVisible(key) {
return colVisible[key] !== false
}
/** 单列显隐切换(供 ColumnSettings 组件 @toggle 调用) */
function toggleColumn(key, visible) {
if (Object.prototype.hasOwnProperty.call(colVisible, key) || columns.some(c => c.key === key)) {
colVisible[key] = !!visible
}
}
function resetColumns() {
columns.forEach(c => {
colVisible[c.key] = c.fixed ? true : c.defaultVisible !== false
})
}
return { colVisible, isColVisible, toggleColumn, resetColumns }
}