A-A+
LayUI – Table的简单使用方式
最近,又需要写点前端页面了,半路出家的我又接触了一些LayUI,对于Table的使用简单总结一下。
本文需要简单了解一下LayUI,了解LayUI模块的引入方式。
表格的HTML代码如下:
<table id="tableTest" lay-filter="tableTest"></table>
<!-- 操作列的HTML模板 -->
<script type="text/html" id="tmplToolBar">
<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i
class="layui-icon layui-icon-edit"></i>编辑</a>
</script>
从Array加载数据
简单的示例代码如下:
table.render({
elem: '#tableTest' //表格的唯一标识
, data: [] //传入的Array
, cols: [[ //所拥有的列
{type: 'checkbox', fixed: 'left'}
, {field: 'contractName', minWidth: 100, title: '合同名称', fixed: 'left'}
, {field: 'signedDate', title: '签订日期', minWidth: 100, templet: function (d) {
//函数式模板
return d.signedDate ? util.toDateString(d.signedDate, 'yyyy-MM-dd') : null;
}
}
, {title: '操作', minWidth: 100, align: 'center', fixed: 'right', toolbar: '#tmplToolBar'}
]]
, page: false //是否分页
, text: {
none: '暂无相关数据'
}
});
从远程加载数据
简单的示例代码如下:
table.render({
elem: '#tableTest' //表格的唯一标识
, url: '/test' //远程url地址
, method: 'post' //请求方式
, cols: [[ //所拥有的列
{type: 'checkbox', fixed: 'left'}
, {field: 'contractName', minWidth: 100, title: '合同名称', fixed: 'left'}
, {field: 'signedDate', title: '签订日期', minWidth: 100, templet: function (d) {
//函数式模板
return d.signedDate ? util.toDateString(d.signedDate, 'yyyy-MM-dd') : null;
}
}
, {title: '操作', minWidth: 100, align: 'center', fixed: 'right', toolbar: '#tmplToolBar'}
]]
, page: false //是否分页
, text: {
none: '暂无相关数据'
}
});
监听操作列触发事件
比如在上面的代码中,操作列是通过模板来渲染的,模板中包含一个“编辑”按钮,当点击此按钮时,希望触发指定事件,可以这么做:
//监听工具条
table.on('tool(tableTest)', function (obj) {
if('edit' == obj.event) {
//可以在这里写触发事件希望执行的代码
}
});
动态加载指定列的数据
有个需求,指定的表格显示数据库中所有的文章。此表格中的某列需要显示该文章的所有标签。
表格的HTML代码可以这样声明:
<table id="tableTest" lay-filter="tableTest"></table>
<script type="text/html" id="tmplTags">
<span data-id="{{d.id}}"></span>
</script>
JavaScript代码如下:
table.render({
elem: '#tableTest'
, url: '/test'
, method: 'post'
, cols: [[
{type: 'checkbox', fixed: 'left'}
, {field: 'name', title: '名称', minWidth: 100}
, {field: 'tags', title: '标签', width: 160, templet: '#tmplTags'}
]]
, page: true
, text: {
none: '暂无相关数据'
}
, done: function(res, curr, count){
//找表格中的所有span,进行替换
//也可以按指定的方式查找,进行替换
this.elem.next().find('td>div>span').each(function (index, value) {
var id = value.getAttribute('data-id');
//异步填充标签信息
$.ajax({
url: "/tags/" + id
, type: "GET"
, dataType: 'json'
, done: function (res) {
value.innerHTML = res.data;
}
});
});
}
});
至此,简单的总结了一下。如有错误,欢迎指正。
