项目中需要使用到layui局部刷新模板,而layui文档上却没有写出来方法,自己看了下源码 ,才知道怎么用,贴出来和大家一起分享
<!--这里假设我有一个模板-->
<script type="text/html" template lay-url="xxx" id="TPL_layout">
<div lay-templateid="TPL_layout">
、<!--你的模板内容-->
</div>
</script>
<!--以下为js -->
<!--当需要刷新的时候 注意 id -->
layui.view('TPL_layout').refresh();
from.render();
<!-- 如果模板内有表单等元素 也需要重新渲染
如加上 from.render();
-->
<!--为什么多一个 div 包裹了一下,我们来看一下源码 -->
//局部刷新模板
Class.prototype.refresh = function(callback) {
var that = this,
next = that.container.next(),
templateid = next.attr('lay-templateid');
<!--这里读取不到id 就直接返回了而不刷新 -->
if(that.id != templateid) return that;
that.parse(that.container, 'refresh', function() {
that.container.siblings('[lay-templateid="' + that.id + '"]:last').remove();
typeof callback === 'function' && callback();
});
return that;
};