碎碎念
LayUI 是一个俊秀的轻量级的UI框架。它涵盖了from元素、layer弹框、table静态/动态数据表格、文件上传、富文本编辑、同时整合了Eacharts数据可视化组件等。之所以我说它是俊秀的,一方面UI审美是比较符合时代趋势的,简约不简单。同时,它跟easyUI极其类似,都是依赖数据就能运行的UI框架。如果你想详细了解LayUI [请戳这里]
为什么会有这篇文章?
我们先来看官网Demo例子,乍一看,好像没啥毛病,它是帮我们实现了数据表格的呈现。
但是实现这个数据表格的js代码是非常的臃肿。所以,我认为语义化封装势在必行。
所以就有了这篇文章。
![](http://itdoer.cn/files/49ced544-d4b0-4040-ad89-1d152ced6a60.png)
![](http://itdoer.cn/files/cf52ea80-dba6-42ed-9562-74a3282a8887.png)
封装后的效果
是不是感觉代码少了很多?其实原理就是,通过配置,让LayuiTable对象在浏览器解析前,构建出来layui的table。让你写更少,做更多!哈哈,反正我比较推崇。一方面是为了效率,另一方面是为易于维护。
![](http://itdoer.cn/files/d1f881e1-c482-4842-bb85-dc3486947eb8.jpg)
实现代码
<!DOCTYPE html>
<html>
<head>
<title>用js对象编码方式 封装layui table</title>
<script src="./table.js"></script>
<link rel="stylesheet" type="text/css" href="./layui/css/layui.css">
<script src="./layui/layui.all.js"></script>
</head>
<body>
<script>
var table = new LayuiTable();
table.setCols([[
{field:'ylyLhl',title:'硫含量',unresize:true}
]])
.setElem("mytable")
.setUrl("http://10.112.10.6:8080/collect/yyplfx/lishiData")
.setAllColUnResize()
// 注释部分是非必要
// .setPageLimits([10,20,30,40,50,100,200])
// .addTool('增加',function(){
// console.log('你点击了增加'+JSON.stringify(data));
// })
// .hiddenDefaultToolbar()
// .addToolbar('批量删除',function(){
// console.log('您点击了批量删除'+JSON.stringify(data));
// })
// .setToolbarWidth(500)
// .addDoneJsFunc(function(){
// console.log('加载完成!');
// })
.render();
console.log(table);
</script>
</body>
</html>
附上封装代码
这里不写注释了,相信用过layui的同学都能理解。
function LayuiTable() {
this.elem = "";
this.pageName = 'page';
this.limitName = 'limit';
this.limits = [10,20,30,50,100,200];
this.cols = [[]];
this.cellMinWidth = 60;
this.page = {
layout: ['prev', 'page', 'next', 'skip','limit', 'count']
,curr: 1
,groups: 1
,first: false
,last: false
}
this.defaultToolbar = ['filter', 'print', 'exports'];
this.toolbars = [];
this.tools = [];
this.hover = null;
this.toolbarTitle = '操作';
this.toolbarFixed = 'right';
this.chooseBtnType = {type:'checkbox'};
this.toolbarWidth = 150;
this.doneJsFuncs = [];
this.allColsUnResize = false;
}
LayuiTable.prototype.render = function() {
this.cols[0].unshift(this.chooseBtnType);
this.page['limits'] = this.limits;
if(this.allColsUnResize && this.cols ){
for(var i = 0 ; i < this.cols.length ; i++){
var col = this.cols[i];
col["unresize"] = true;
}
}
if(this.tools.length>0){
this.cols[0].push({
fixed: this.toolbarFixed,
title:this.toolbarTitle,
toolbar: '#'+this.elem+'Tool',
width:this.toolbarWidth
});
}
var html = `
<table class="layui-hide" id="`+this.elem+`" lay-filter="`+this.elem+`"></table>`;
if(this.toolbars.length >0 ){
html+=`
<script type="text/html" id="`+this.elem+`Toolbar">
<div class="layui-btn-container">
`;
for(var key in this.toolbars){
var toolbar = this.toolbars[key];
html+=`<button class="layui-btn layui-btn-sm `+(toolbar.styleClass?toolbar.styleClass:'')+`" lay-event="`+this.elem+`Toolbar`+key+`">`+toolbar.title+`</button>`;
}
html+=`
</div>
</script>`;
}
if(this.tools.length >0 ){
html+=`
<script type="text/html" id="`+this.elem+`Tool">
`;
for(var key in this.tools){
var toolbar = this.tools[key];
html+=`<a class="layui-btn layui-btn-xs `+(toolbar.styleClass?toolbar.styleClass:'')+`" lay-event="`+this.elem+`Tool`+key+`">`+toolbar.title+`</a>`;
}
html+=`</script>`;
}
html+=`
<script>
layui.use("table", function(){
var table = layui.table;
table.render({
elem: '#`+this.elem+`'`;
if(this.toolbars.length>0){
html+=`,toolbar:'#`+this.elem+`Toolbar'`;
}
if(this.defaultToolbar){
html+=`,defaultToolbar:`+JSON.stringify(this.defaultToolbar);
}
html+= `,url:'`+this.url+`'
,cellMinWidth: 80
,cols:`+JSON.stringify(this.cols)+`
,page:`+JSON.stringify(this.page)+`
,done: function(res, curr, count){`
for(var key in this.doneJsFuncs){
var done = this.doneJsFuncs[key];
html+=`
var `+this.elem+`Done`+key+` = `+done.toString()+`;
`+this.elem+`Done`+key+`();
`;
}
html+=` }
});
`;
if(this.toolbars.length >0 ){
html+=`
table.on('toolbar(`+this.elem+`)', function(obj){
var checkStatus = table.checkStatus('`+this.elem+`');
var data = checkStatus.data;
switch(obj.event){`;
for(var key in this.toolbars){
var toolbar = this.toolbars[key];
html+=`
case '`+this.elem+`Toolbar`+key+`':
var `+this.elem+`Toolbar`+key+` = `+toolbar.jsfunc.toString()+`;
`+this.elem+`Toolbar`+key+`();
break;
`;
}
html+=` };
});`;
}
if(this.tools.length >0 ){
html+=`
table.on('tool(`+this.elem+`)', function(obj){
var checkStatus = table.checkStatus('`+this.elem+`');
var data = obj.data;
switch(obj.event){`;
for(var key in this.tools){
var toolbar = this.tools[key];
html+=`
case '`+this.elem+`Tool`+key+`':
var `+this.elem+`Tool`+key+` = `+toolbar.jsfunc.toString()+`;
`+this.elem+`Tool`+key+`();
break;
`;
}
html+=` };
});`;
}
html+=`});
</script>
`;
document.write(html);
return this;
};
LayuiTable.prototype.setDefaultToolbar = function(toolbar) {
this.defaultToolbar = toolbar;
return this;
};
LayuiTable.prototype.setAllColUnResize = function() {
this.allColsUnResize = true;
return this;
};
LayuiTable.prototype.hiddenDefaultToolbar = function() {
this.defaultToolbar = [];
return this;
};
LayuiTable.prototype.setToolbarWidth = function(toolbarWidth) {
this.toolbarWidth = toolbarWidth;
return this;
};
LayuiTable.prototype.addDoneJsFunc = function(jsFunc) {
this.doneJsFuncs.push(jsFunc);
return this;
};
LayuiTable.prototype.setChooseBtnType = function(type) {
this.chooseBtnType = {
type: type == 'checkbox' ? type :'radio'
}
return this;
};
LayuiTable.prototype.hover = function(jsfunc) {
this.hover = jsfunc;
return this;
};
LayuiTable.prototype.addToolbar = function(title,jsfunc,styleClass) {
this.toolbars.push({
title:title,
jsfunc:jsfunc,
styleClass:styleClass
});
return this;
};
LayuiTable.prototype.addTool = function(title,jsfunc,styleClass) {
this.tools.push({
title:title,
jsfunc:jsfunc,
styleClass:styleClass
});
return this;
};
LayuiTable.prototype.setPsgeLast = function(last) {
this.page['last'] = last;
return this;
};
LayuiTable.prototype.setPsgeFirst = function(first) {
this.page['first'] = first;
return this;
};
LayuiTable.prototype.setPageGroups = function(groups) {
this.page['groups'] = groups;
return this;
};
LayuiTable.prototype.setPageCurr = function(curr) {
this.page['curr'] = curr;
return this;
};
LayuiTable.prototype.setPageLayout = function(layout) {
this.page['layout'] = layout;
return this;
};
LayuiTable.prototype.setPage = function(page) {
this.page = page;
return this;
};
LayuiTable.prototype.setCellMinWidth = function(cellMinWidth) {
this.cellMinWidth = cellMinWidth;
return this;
}
LayuiTable.prototype.setLimitName = function(limitName) {
this.limitName = limitName;
return this;
}
LayuiTable.prototype.setCols = function(cols) {
this.cols = cols;
return this;
}
LayuiTable.prototype.setElem = function(elem) {
this.elem = elem;
return this;
}
LayuiTable.prototype.setUrl = function(url) {
this.url = url;
return this;
}
LayuiTable.prototype.setPageLimits = function(limits) {
this.limits = limits;
return this;
}
LayuiTable.prototype.setPageName = function(pageName) {
this.pageName = pageName;
return this;
}