Introduce a,

Before we use Layui, we need to know what layui is. I think it’s best summed up in the author’s wise words: a front-end framework for back-end programmers. More specifically, it’s a front-end framework that encapsulates CSS and JS, Ajax, and so on, with a degree of encapsulation that is sometimes unfriendly to programmers. But layui is a good tool for people with mediocre front-end skills.


Start using Layui

How to use: Download and import the project, and then reference it

<script th:src="@ {/ jquery - 3.3.1. Min. Js}"></script>
<script th:src="@{/layui/layui.js}"></script>
<link rel="stylesheet" th:href="@{/layui/css/layui.css}" />
Copy the code

First reference jquery, then layui.js and layui.css. Why must it be local? No CDN? As mentioned above, Layui is packaged so “well” that the programmer’s autonomy is limited, and the source code of Layui, such as CSS styles, needs to be modified — this is how Layui should be used, not simply used.

Layui modules: LayUI is modular, including form, Layer, LayDate, LayPage and other modules, it is these modules make up the complete LayUI. When using Layui, you need to specify the module you are using.


Start using Layui:

<script>
  layui.use(['mod1'.'mod2'].function(args){
    var mo1 = layui.mod1
       ,mo2 = layui.mod2;
  });
</script>
Copy the code

Layui form

The following uses the most common form forms in HTML to demonstrate layui. HTML part:

<fieldset class="layui-elem-field layui-field-title" style="margin-top:30px;">
    <legend style="text-align:center;">Sign up for a new account</legend>
</fieldset>
<form id="reform" class="layui-form layui-form-pane"  th:action="@{/user/register.html}" method="POST">
    <div class="layui-form-item">
        <label class="layui-form-label">email</label>
        <div class="layui-input-block">
        <input type="text" name="email" lay-verify="email" placeholder="Please enter" autocomplete="off" class="layui-input" />
        </div>
    </div>
         
    <div class="layui-form-item">
        <label class="layui-form-label">The user name</label>
        <div class="layui-input-block">
            <input type="text" name="name" lay-verify="required" placeholder="Please enter" autocomplete="off" class="layui-input" />
        </div>
    </div>
         
    <div class="layui-form-item">
        <label class="layui-form-label">password</label>
        <div class="layui-input-block">
            <input type="password" name="password"  lay-verify="pass" placeholder="Please enter your password" autocomplete="off" class="layui-input" />
        </div>
    </div>
        
    <div class="layui-form-item">
        <label class="layui-form-label">Repeat the password</label>
        <div class="layui-input-block">
            <input type="password" name="repassword"   lay-verify="repass" placeholder="Please enter your password" autocomplete="off" class="layui-input" />
        </div>
    </div>
        
    <div class="layui-form-item">
        <button  class="layui-btn layui-btn-fluid" lay-submit="" lay-filter="demo1">registered</button>
    </div>
        
    <div style="text-align:center; margin-top:15px;">
        <input type="checkbox" name="agree"  lay-skin="primary" checked=""/>I have read and agree<a href="#" id="agreementLink">Privacy Policy</a>
    </div>
</form>
Copy the code

Javscript parts:

<! -- jsfor form input and submit -->
<script>
layui.use(['form'].function(){
  var form = layui.form;
 
  // Customize the validation rule
  form.verify({
    pass: [/ (. +) 6, 12 {} $/.'Password must be 6 to 12 digits'].repass:function(value){
    	var pvalue = $("input[name='password']").val();
    	if(pvalue! =value){return "Two different passwords entered."; }}});// Listen for submissions
  form.on('submit(demo1)'.function(data){
	var agreeChecked = data.field.agree;
    if(agreeChecked! ="on"){
    	msg("Did not agree to the privacy policy.");
    	return false;// Block form submission}}); });</script>
Copy the code

Effect:

4. Layui pop-up layer

Pop-ups are pretty common, but the basic HTML/JS method is the ugly Alert (“”) method. Layui includes a popup module called Layer. There are two ways to use layer: first, declare layui.use as above, and then use it in function after use. Import a separate Layer module file and use it directly. The first method is not discussed, but the second method is introduced here.

Example:

function msg(msg){
 	// Dark green dark blue wind
    layer.alert(msg, {
      title:'message'
      ,skin: 'layui-layer-molv' // Style class name
	  ,closeBtn: 0
	 },function(index){
		layer.close(index);/ / close
	 });
}
Copy the code

Effect:

Layer can not only pop up the prompt box, but also do some interesting and useful dynamic effects, and even load a pop-up HTML interface. For more information, please refer to layer’s official website.


5. Upload layui files

Let’s look at layui’s file upload module

<! -- Upload image -->
<div class="layui-tab-item">
    <div class="layui-upload">
        <button type="button" class="layui-btn layui-btn-normal" id="headButton">
            <i class="layui-icon">&#xe67c;</i>Choose picture</button>&nbsp; &nbsp; &nbsp; &nbsp;<button type="button" class="layui-btn" id="headAddButton">To upload</button>
    </div>
               
    <div class="layui-inline layui-word-aux" style="margin-top:20px;">
        <label>Note: JPG, PNG and GIF formats are supported, and the file size should be less than 10MB</label>
    </div>
</div>
Copy the code
<! -- File upload --><script>
layui.use('upload'.function(){
	var $ = layui.jquery
	,upload = layui.upload;
	
	// The file will not be uploaded automatically after being selected
	upload.render({
		elem: '#headButton'
		,url: getRootPath()+'/user/uploadPicture'
		,size: 10*1024 //10*1024KB = 10MB
		,accept: 'images'
		,acceptMime: 'image/jpg,image/png,image/gif'
		,auto: false
		,bindAction: '#headAddButton'
		,done: function(res){
			msg(res.msg);
			// Refresh the avatar address
			var resUrl = res.url;
			if(resUrl! ="") {document.getElementById("userImg").src=getRootPath()+ resUrl; }}}); });</script>
Copy the code

Back end (in java-spring-Controller class) :

@Autowired
FileService fileService;

@RequestMapping(path="/uploadPicture",method= {RequestMethod.POST})
@ResponseBody
public Map<String,Object> uploadFile(@RequestParam("file")MultipartFile file,HttpServletRequest request){
	Map<String,Object> map = new HashMap<String,Object>();
	String path = fileService.uploadImg(file, "head");// The service layer saves the file
	
	// The return value must be written like this -- conforming to the callback interface of the Upload module
	map.put("code".0); //0 indicates success
	map.put("msg"."Upload successful");
	map.put("data"."");
	map.put("url", path);
	return map;
}	
Copy the code

Upload Interface and return value:

// Upload interface
upload.render({
  elem: '#id'
  ,url: '/api/upload/' / / mandatory
  ,method: ' '  // Optional. HTTP, default post
  ,data: {} // Optional. Additional arguments, such as {id: 123, ABC: 'XXX '}
});   

/ / the return value
{
  "code": 0
  ,"msg": ""
  ,"data": {
    "src": "http://cdn.layui.com/123.jpg"}}Copy the code

For more information on Javaweb file uploads, see my other blog: making it easy to upload Javaweb files

Effect:

The Upload module of Layui can configure file size, format and preview in the front end, as well as batch upload and retransmission functions. See the Upload module of Layui for more information.


6. Layui paging

Paging is also often used in web sites, where back-end paging is easy to implement, but not ideal for the front end. Layui provides its own paging module, LayPage.

<div id="allNewsDiv"></div>
<div id="demo"></div>
Copy the code
layui.use(['element'.'laypage'].function(){
	  var element = layui.element
	  ,laypage = layui.laypage;
	  
	  $.ajax({
		 url:getRootPath()+'/news/count'
		 ,type:'GET'
		 ,async:true  //false indicates non-asynchronous, that is, synchronous, that is, only after the request is processed.
		 ,data: {"page":1."limit":10},dataType:'json'
		 ,success:function(alldata){
			var numbers = alldata.count;
		    The total number of pages is greater than the total number of pages
			laypage.render({
			    elem: 'demo'
			    ,count: numbers// Total number of data
			    ,first: 'home'
			    ,last: 'back'
			    ,jump: function(obj){
			      $.ajax({
		            url:getRootPath()+'/news/list'
		            ,type:'GET'
		            ,async:true
		            ,data: {"page":obj.curr, "limit":obj.limit}
		            ,dataType:'json'
		            ,success:function(data){
		            	var shtml = getNewsContentHTML(data);//js processes the data and populates the div
		            	document.getElementById("allNewsDiv").innerHTML=shtml; }}); }}); }}); });Copy the code

As shown above, the event for paging jumps takes place in jump, where you write an AJAX request, get the page and limit parameters from jump’s obj parameter, and then process the request after it completes and returns data


7. Layui data table

Table is a common function, but JS splicing HTML table is a more cumbersome and error-prone thing.

<! -- team pagination table -->
<table class="layui-hide" id="teamTable" lay-filter="teamTool">
</table>
Copy the code
<script> layui.use('table',function(){ var table = layui.table; Table.render ({elem:'#teamTable',method:'get',url:getRootPath()+'/team/admin/list' // return a list <TeamMember> , cellMinWidth: 80, cols: [[{field: "id", the title: "id", sort: true}, {field: 'name, the title:' name '}, {field: 'birth, {field:'position', title:' identity '},{field:'information', Title: 'personal information'}, {field: 'right, title:' operation, the toolbar: '# barDemo}]], page: true / / open the paging}); Table. on(' teamTool (teamTool)', function(obj){// Tool is the name of the toolbar event, and test is the attribute of the original table container. Var layEvent = obj.event; Var tr = obj.tr; // Get the value of lay-event (or event). // Get the DOM object console.log("id:"+data.id) for the current tr; If (layEvent === 'detail'){// view //do something layer. MSG ('ID: Else if(layEvent === 'del'){// Delete layer.confirm(' Confirm to delete personal information? ', function(index){ //do something layer.close(index); }); } else if(layEvent === 'edit'){// Edit //do something}}); }); </script> <! -- tools --> <script type="text/html" id="barDemo"> <a class="layui-btn layui-btn-primary layui-btn-xs" </a> <a class=" layui-bTN layui-btn-xs" lay-event="edit"> Edit </a> <a class=" layui-bTN layui-btn-danger Layui-btn-xs "lay-event="del"> Delete </a> </script>Copy the code

Effect:


Ok, so much for the introduction of Layui. For more detailed and in-depth understanding, please go to layui’s official website.