以前layui分頁使用Jquery拼接元素進行渲染,感覺比較麻煩而且不夠優雅,後來使用了其他分頁方式一直沒有時間更新,現在記錄下用layui的模板引擎laytpl對分頁數據進行渲染。
一:引入layUI的相關資源
<link rel="stylesheet" href="${ctxPath}/vendor/layui-v2.4.5/layui/css/layui.css">
<script src="${ctxPath}/vendor/layui-v2.4.5/layui/layui.js"></script>
<script src="${ctxPath}/vendor/jquery.min.js"></script>//引入jquery包
二:html頁面代碼
<div class="layui-main g-main">
<div class="layui-row">
<div class="layui-col-xs12">
<table class="layui-table">
<thead>
<tr>
<th>積分類型</th>
<th>積分原因</th>
<th>積分值</th>
<th>創建時間</th>
</tr>
</thead >
<tbody id="tableList">
//使用模板引擎渲染數據
</tbody>
</table>
//分頁渲染
<div id="page" style="text-align: center;"></div>
</div>
</div>
</div>
三:模板js
<script id="tpl" type="text/html">
{{# layui.each(d, function(index, item){ }}
<tr>
<td>{{item.type}}</td>
<td>{{item.reason}}</td>
<td>{{item.sum}}</td>
<td>{{item.time}}</td>
</tr>
{{# }); }}
</script>
四:分頁加載渲染
爲了便於大家查看,就不按方法拆分爲幾個代碼片段分別展示了,注意看代碼註釋說明。
<script>
layui.use(['laytpl','laypage','jquery','form'],function(){
let laypage = layui.laypage,$ = layui.$, laytpl = layui.laytpl;
//模板引擎--自定義工具類
let _tplUtil = {
//請求數據
request : function(param){
$.ajax({
type : param.method || 'get',
url : param.url || '',
dataType : param.type || 'json',
data : param.data || '',
async : param.async || true,
success : function(res){
typeof param.success === 'function' && param.success(res);
},
error : function(err){
typeof param.error === 'function' && param.error(err.statusText);
}
});
},
//渲染數據到模板,返回html
renderHtml : function(htmlTemplate, data){
let template = laytpl(htmlTemplate),
result = template.render(data);
return result;
},
//**導入並渲染模板數據**
loadTplData : function(tplId,elementId,url,params) {
// 模版引擎導入
let html = $('#'+tplId).html();
let element = $('#'+elementId);
_tplUtil.request({
type: 'get',
url: url,
dataType: 'json',
data: params,
async: false,
success : function(res){
element.innerHTML = _tplUtil.renderHtml(html,res)
},
error: function(res){
console.log(res);
}
})
}
}
//請求參數的封裝
function showData(pageNo,pageSize) {
let params = {
pageNo: pageNo,
pageSize: pageSize
//...如果還需要進行條件查詢,可在此傳入查詢參數,進行參數封裝
}
//調用模板引擎加載並渲染數據
_tplUtil.loadTplData('tpl','tableList','/recard/findData',params);
}
//分頁渲染
$.get('/recard/getTotal', function (total) {
laypage.render({
elem: $("#page") //分頁元素
, count: total //數據總數,從服務端得到
, limit: 10 //默認每頁顯示條數
, limits: [10, 20, 30] //可選擇的每頁顯示條數
, curr: 1 //起始頁
, groups: 5 //連續頁碼個數
, prev: '上一頁' //上一頁文本
, netx: '下一頁' //下一頁文本
, first: 1 //首頁文本
, last: 100 //尾頁文本
, layout: ['prev', 'page', 'next', 'limit', 'refresh', 'count', 'skip']
//跳轉頁碼時調用
, jump: function (obj, first) { //obj爲當前頁的屬性和方法,第一次加載first爲true
pageNo = obj.curr;
pageSize = obj.limit;
//調用函數封裝參數,加載數據
showData(obj.curr, obj.limit);
}
})
}, 'json');
});
</script>
以上代碼不侷限於table表格分頁,如果只是table表格分頁查詢,推薦使用layui自帶分頁功能,可以參考下面的博客。
表格分頁推薦:使用layui的table組件自帶分頁功能(異步,含條件查詢)點這裏