layui数据表格列动态显示或隐藏
时间: 2023-05-12 22:06:25 浏览: 71
可以使用 layui 的 table 模块中的 cols 属性来实现数据表格列的动态显示或隐藏。具体实现方法可以参考以下代码:
// 定义表格列
var cols = [
{field: 'id', title: 'ID'},
{field: 'name', title: '姓名'},
{field: 'age', title: '年龄'},
{field: 'gender', title: '性别'},
{field: 'address', title: '地址'}
];
// 初始化表格
var table = layui.table;
table.render({
elem: '#demo',
cols: [cols],
data: []
});
// 动态显示或隐藏列
function toggleColumn(field, visible) {
var index = cols.findIndex(function(col) {
return col.field === field;
});
if (index >= 0) {
cols[index].hide = !visible;
table.reload('demo', {
cols: [cols]
});
}
}
// 示例:隐藏年龄列
toggleColumn('age', false);
相关问题
通过后台传递的标识,layui数据表格列动态显示或隐藏
可以使用 layui 的 table 模块提供的 cols 属性来动态显示或隐藏数据表格列。具体实现方法可以参考以下代码:
// 定义数据表格的列信息
var cols = [
{field: 'id', title: 'ID', width: 80},
{field: 'username', title: '用户名', width: 120},
{field: 'email', title: '邮箱', width: 200},
{field: 'phone', title: '手机号码', width: 120},
{field: 'status', title: '状态', width: 80},
{field: 'create_time', title: '创建时间', width: 160},
{field: 'update_time', title: '更新时间', width: 160},
];
// 根据后台传递的标识动态显示或隐藏数据表格列
if (isShowId) {
cols[0].hide = false;
} else {
cols[0].hide = true;
}
if (isShowEmail) {
cols[2].hide = false;
} else {
cols[2].hide = true;
}
if (isShowPhone) {
cols[3].hide = false;
} else {
cols[3].hide = true;
}
// 渲染数据表格
layui.table.render({
elem: '#demo',
url: '/api/user/list',
cols: [cols],
page: true
});
注意,isShowId、isShowEmail、isShowPhone 都是后台传递的标识,表示是否显示对应的列。如果为 true,则显示该列;如果为 false,则隐藏该列。
layui table 修改列的显示或隐藏
要修改Layui表格中列的显示或隐藏,您可以使用Layui的hideColumn和showColumn方法。
例如,如果您想隐藏表格中的第二列,可以使用以下代码:
```
table.hideColumn(1);
```
如果您想显示该列,可以使用以下代码:
```
table.showColumn(1);
```
请注意,这些方法需要在您的表格渲染后才能调用。如果您希望在表格渲染之前设置默认的列可见性,您可以使用Layui表格的cols属性中的hide和show属性。例如,以下代码将在渲染表格时隐藏第二列:
```
var table = layui.table;
table.render({
elem: '#test',
cols: [[
{field: 'id', title: 'ID'},
{field: 'username', title: '用户名', hide: true}, // 隐藏第二列
{field: 'email', title: '邮箱'}
]],
data: [{
id: 1,
username: 'test',
email: 'test@test.com'
}]
});
```