搞定Layui表格的动态loading提示:别在`done`回调里白费功夫 很多人尝试通过 `table.render()` 的 `done` 回调来实现渲染前的loading动态更新,但这其实是无效的。因为 `done` 回调是在表格渲染完成后才触发的,与“渲染前”的时间点完全不符。 真正的需求场
加载中…table.render() 的配置中,设置 request 选项,以接管 beforeSend 和 error 回调。beforeSend 回调中启动定时器,每秒更新loading文字;在 error 或 done 回调中清除定时器并隐藏loading元素。
table.render({
elem: '#demo',
url: '/api/list',
request: {
// 此处参数将透传到内部的 $.ajax 调用
beforeSend: function(xhr, settings) {
const loadingEl = $('#table-loading');
loadingEl.show();
const timer = setInterval(() => {
const dots = ['.', '..', '...'];
const idx = (dots.indexOf(loadingEl.text().trim().slice(-3)) + 1) % 3;
loadingEl.text('加载中' + dots[idx]);
}, 1000);
// 将定时器挂载到 xhr 对象上,便于后续清理
xhr._loadingTimer = timer;
}
},
done: function(res, curr, count) {
$('#table-loading').hide();
if (this.request && this.request.beforeSend) {
// 清理可能遗留的定时器
clearInterval(this.request.beforeSend.toString().includes('_loadingTimer')
this.request.beforeSend._loadingTimer : null);
}
}
});
这里有一个实用技巧:将定时器挂载到 `xhr` 实例上,而不是存入全局变量。这样在后续清理时可以直接通过 `xhr._loadingTimer` 定位,避免多个表格同时存在时相互干扰。
loading: true 后,Layui 会在表格容器内插入一个 .layui-table-loading 元素,但其DOM结构不可预测,且没有提供事件绑定入口。done、error,以及可能的 before(例如用户取消操作)回调中,都执行 clearInterval 清理定时器。xhr 实例或表格实例的私有属性上,例如 this._loadingTimer。table.reloadData() 方法,在发起新请求前务必先清除旧的定时器,否则会出现多个定时器叠加的混乱情况。侠游戏发布此文仅为了传递信息,不代表侠游戏网站认同其观点或证实其描述