Layui 数据表格动态cols(字段)动态变化

                                                             Layui数据表格动态cols(字段)动态变化

1、代码

<!-- HTML -->
<!-- 表格载体 -->
<div class="layui-form layui-card-header"><div class="layui-inline"><label class="layui-form-label">分组类型</label><div class="layui-input-inline"><input type="hidden" name="group_type"/><select multiple="multiple" lay-filter="group_type"><option value="">请选择分组类型</option><option value="hobby" selected>爱好</option><option value="age">年龄</option><option value="date">日期</option></select></div></div><div class="layui-inline"><button class="layui-btn" lay-submit lay-filter="LAY-table-search"><i class="layui-icon layui-icon-search"></i></button></div>
</div>
<table id="table-id" lay-filter="LAY-table"></table>//JS
<script>//JSlayui.use(['table', 'form', 'multiSelect'], function () {let table = layui.table,form = layui.form;         //表格let tableObj = table.render({elem: '#table-id',   //挂载对象,表IDurl: '/.../.../...',    //数据来源路径cols: [[{field: 'hobby', title: '爱好'},{field: 'come_in', title: '收入'},{field: 'come_out', title: '支出'}]],text: { //自定义文本,如空数据时的异常提示等。none: '暂无数据!'},where:{'target_date':'2020-02'},//查询条件page: false, //关闭分页parseData: function(res) {  //res 即为原始返回的数据return {code: res.code,msg: res.msg,count: res.data.count,data: res.data.data}},done(res, curr, count){}});//监听下拉框的值let groupArray = ['hobby'];  //默认按爱好分组form.on('select(group_type)', function(data) {setTimeout(() => {	//选中获取值异常问题let value = data.value;let bool = $(data.othis).find('.layui-this').children('div').hasClass('layui-form-checked');//判断是否勾选let index = $.inArray(value, groupArray);if (bool) { //如果选中;if(index == -1){  //数组没值,groupArray.push(value);   //把值压入数组}} else {    //如果取消选中if(index != -1){  //数组中存在groupArray.splice($.inArray(value, groupArray), 1);   //移除数组指定元素}}$('input[name="group_type"]').val(JSON.stringify(groupArray));}, 100);})//监听搜索按钮form.on('submit(LAY-table-search)', function(data){let field = data.field;let tableCols = assembleTableCol(groupArray);	//重新定义标题那行//执行重载table.reload('LAY-table', { //通用渲染方式where: field,   //搜索的参数page: {curr: 1}, //重新从第 1 页开始cols: tableCols});//或tableObj.reload({   //方法级渲染where: field,   //搜索的参数page: {curr: 1}, //重新从第 1 页开始cols: tableCols});});//重新拼接数组标题行function assembleTableCol(groupArray){let thisCols = [];  //定义标题空间let defaultField = [    //定义通用列{field: 'come_in', title: '收入'},{field: 'come_out', title: '支出'}];let groupField = {  //hobby,age,date 对应下拉框的值'hobby': {field: 'hobby', title: '爱好'},'age': {field: 'age', title: '年龄'},'date': {field: 'date', align:'center',title: '日期'},};let length = groupArray.length;for (let i=0; i<length; i++){ //追加动态标题let addObj = groupField[groupArray[i]];thisCols.push( addObj );}let defaultLength = defaultField.length;for(let j=0;j<defaultLength;j++){   //追加默认标题thisCols.push( defaultField[j]);}return [thisCols];  //注意结果为:array[0]=thisCols}});
</script>

 

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注