最近在使用layui的时候,在表格填充的时候发现一件比较坑的事情,那就是当我表里存储的是枚举值(即数据库中存1.2,1代表男,2代表女)的时候,想在前台显示相应的类型,但是layui没有提供我想象中的简便的工具。
我想象中的工具是这样的 (此处,想象画重点,实际上layui并没有这样的方法,只是个人觉得如果方法是这样的话书写就很方便):
但是我发现layui并没有给类似于这样的方法,而是有别的方法,话不多说,上代码
这是我原本要加载的表格,但是现在sex(性别)里面存的是1(男)和2(女),这样的话表格里显示的就直接是1和2
table.render({ elem: '#commodity', //指定原始表格元素选择器(推荐id选择器) url: www.baidu.com, //数据接口 page: true, //开启分页 cellMinWidth: 120, //表格最小宽度 limit:10, //每页起始显示条数 where: {}, //查询条件 cols: [ [ //表头 {type: 'checkbox', align: 'center', fixed: 'left'} , {field: 'id', align: 'center', title: '编号'} , {field: 'name', align: 'center', title: '姓名'} , {field: 'sex', align: 'center', title: '性别'} , {field: 'phone', align: 'center', title: '手机号码'} ] ] });所以我对代码做以下更改:
table.render({ elem: '#commodity', //指定原始表格元素选择器(推荐id选择器) url: www.baidu.com, //数据接口 page: true, //开启分页 cellMinWidth: 120, //表格最小宽度 limit:10, //每页起始显示条数 where: {}, //查询条件 cols: [ [ //表头 {type: 'checkbox', align: 'center', fixed: 'left'} , {field: 'id', align: 'center', title: '编号'} , {field: 'name', align: 'center', title: '姓名'} , {field: 'sex', align: 'center', title: '性别', templet: "#stateBar0"} , {field: 'phone', align: 'center', title: '手机号码'} ] ] }); <script type="text/html" id="stateBar0"> <div> {{# if(d.sex=== 1){ }} 男 {{# }else if(d.sex=== 2){ }} 女 {{# }else{ }} {{# } }} </div> </script>在需要添加枚举值的一栏添加 templet: “#stateBar0” ,之后在添加一个js代码块儿,赋予ID stateBar0 ,这样在渲染表格的时候,显示的就是枚举值啦!
这个方法其实是layui提供的模板引擎,这只是其中的一种用法,有兴趣的小伙伴可以去看一下其它的方法:layui模板引擎