Home > Article > Web Front-end > Layui module usage specifications (with code)
Pre-loading
Let’s get straight to the point, it’s more appropriate to just say how to use it. Layui's module loading uses the core layui.use(mods, callback) method. When your JS needs to use the Layui module, we recommend that you use preloading, because this can avoid the trouble of writing layui.use everywhere. You should define it like this in the outermost layer:
/* Demo1.js 使用Layui的form和upload模块 */ layui.use(['form', 'upload'], function(){ //如果只加载一个模块,可以不填数组。如:layui.use('form') var form = layui.form() //获取form模块 ,upload = layui.upload; //获取upload模块 //监听提交按钮 form.on('submit(test)', function(data){ console.log(data); }); //实例化一个上传控件 upload({ url: '上传接口url' ,success: function(data){ console.log(data); } }) });
On-demand loading (not recommended)
If you have obsessive-compulsive disorder, you have extreme requirements for website performance , you do not want to preload the required modules, but load the modules when an action is triggered, then this is allowed. You don’t need to wrap a big layui.use in the outermost layer of your JS, you only need:
* Demo2.js 按需加载一个Layui模块 */ //…… //你的各种JS代码什么的 //…… //下面是在一个事件回调里去加载一个Layui模块 button.addEventListener('click', function(){ layui.use('laytpl', function(laytpl){ //温馨提示:多次调用use并不会重复加载laytpl.js,Layui内部有做模块cache处理。 var html = laytpl('').render({}); console.log(html); }); });
Module namespace
All of Layui The module is bound under the layui object, and is internally completed by the layui.define() method. Each module has a unique name and cannot be occupied. So you don't need to worry about the module's space being polluted, unless you delete layui.mod; when calling a module, you must also use the assignment of the layui object. For example:
layui.use(['layer', 'laypage', 'laydate'], function(){ var layer = layui.layer //获得layer模块 ,laypage = layui.laypage //获得laypage模块 ,laydate = layui.laydate; //获得laydate模块 //使用模块 });
For more layui knowledge, please pay attention to the layui usage tutorial column.
The above is the detailed content of Layui module usage specifications (with code). For more information, please follow other related articles on the PHP Chinese website!