最稳做法是在 cols 中直接设 hide: true;动态隐藏须在 done 回调用 table.hideCol();权限实时切换需深拷贝 cols 后 reload;导出 Excel 需手动配置 export.columns 或 exportData 钩子。

初始化时用 hide: true 控制默认显隐
权限相关的列(比如“操作”“编辑”“删除”)最稳的做法是在 cols 里直接加 hide: true,Layui 2.8+ 原生支持,首帧渲染即生效,不闪屏、不占位、不影响 table.on('tool') 里的 d.id 等字段读取。
常见错误:
-
hide: 'true'或hide: 1—— 必须是布尔值true - 漏写
field—— 后续无法通过字段名定位该列 - 和
unresize: true混用 —— 隐藏列本身不可拖拽,多写纯属冗余
示例配置:
cols: [[
{field: 'id', title: 'ID'},
{field: 'username', title: '用户名'},
{field: 'action', title: '操作', hide: true}
]]
动态隐藏必须在 done 回调里调用 table.hideCol()
权限不是静态的,得等表格渲染完成再判断是否显示某列。不能在 layui.use(['table'], callback) 里直接调 table.hideCol(),此时 DOM 还没生成,调了也白调。
正确时机只在 table.render() 的 done 回调中:
-
table.hideCol('action')接收的是field值,不是标题文字或数组索引 - 恢复显示用
table.showCol('action'),不是 toggle - Layui 2.7+ 才稳定支持,旧版本建议升级或改用初始化
hide: true
示例:
table.render({
elem: '#demo',
url: '/api/list',
done: function(res, curr, count) {
if (!hasPermission('edit')) {
table.hideCol('action');
}
}
});
动态切换显示/隐藏必须走 reload() + 深拷贝 cols
如果权限可实时切换(比如用户点击角色按钮),table.hideCol() 和 table.showCol() 不够用——它们只影响 UI 层,且不保证后续所有状态同步。真实可行路径是:深拷贝当前 cols → 修改目标列 hide 值 → 调 reload({ cols: newCols })。
关键细节:
- 别直接改
tableIns.config.cols[0][2].hide—— 会污染原始配置 - 别用
JSON.parse(JSON.stringify())深拷贝 —— 会丢掉templet函数;现代浏览器优先用structuredClone() -
reload()时不传where和page,表格会回到第 1 页、丢失搜索条件 - 按
field查找列比靠数组索引更可靠,避免加删列后偏移
安全写法:
function toggleActionCol(tableIns, visible) {
const newCols = structuredClone(tableIns.config.cols);
const targetCol = newCols[0].find(col => col.field === 'action');
if (targetCol) targetCol.hide = !visible;
tableIns.reload({
cols: newCols,
where: tableIns.config.where,
page: { curr: tableIns.config.page.curr }
});
}
导出 Excel 时隐藏列不会自动过滤
这是高频盲区:hide: true 只影响 UI 渲染,导出逻辑默认读取原始数据源,所有字段照常输出。权限列即使 UI 上看不见,Excel 里照样出现。
若需导出与视图一致,必须手动干预:
- 用
export.columns显式指定字段,field名必须和列配置完全一致(大小写敏感) - 或用
exportData钩子返回精简后的数组,注意分页时table.cache只存当前页数据 - 多级表头需自己 flatten,只保留叶子节点列
示例(仅导出可见列):
export: {
columns: [
{field: 'id'},
{field: 'username'}
]
}
真正麻烦的点不在怎么写,而在「什么时候该 reload」和「什么时候该重置 export.columns」——这两个动作容易被当成独立任务分别处理,结果导出列和 UI 列对不上,Excel 报错或错位。











