When using Layui-based table components (such astable
When component),Methods are the key to rendering tables. This method allows you to define the display style and data column of the table through configuration objects (
cols
), data source, etc. aboutcols
The problem of how to bind data is actually throughcols
Each object in the array is specified.
Eachcols
Objects in an array usually contain several key properties that determine the display and behavior of table columns:
-
field: This is one of the most important properties, which specifies the name of the corresponding field in the data source (usually a JSON array). This means that
field
The value of should match the key name in the data source you want to display in the table column. - title: This property defines the title of the table column header.
- sort: Whether to allow the column to be sorted, boolean.
- type: Defines the display type of columns, such as date, link, etc. Layui will display in a specific format according to this value.
- templet: This is a function or string template for customizing the display content of a column. If provided, it allows you to dynamically generate HTML content for that column based on the data of the current row.
...: It may also contain other properties such as width (width
), whether to display (hide
), whether to freeze the column (frozen
)wait.
The process of data binding is roughly as follows:
- You passed
Method
cols
Parameters define the columns of the table. - exist
cols
In the array, each object passesfield
The attribute specifies the name of the corresponding field in the data source. - when
When called, Layui will be based on the provided data source (usually through
url
Parameters are obtained asynchronously or passeddata
Parameters are provided directly) andcols
Definition to render tables. - For each row of data, Layui will look up
cols
Each column object defined in the array and usefield
Attribute to get the corresponding value from the current row data. - If specified
templet
, then use the function or template to generate the HTML content of the column; otherwise, the obtained value is displayed directly. - Finally, all rows and columns data are rendered into the table, realizing the binding and display of the data.
in short,cols
Infield
Properties are the key to connecting data sources and table columns. They tell Layui how to find and display data for each column in the data source.
example:
Of course, here are some of the ones that use LayuiMethods and their
cols
Example of configuration. These examples assume that you already have the basic Layui framework integrated into your project.
Example 1: Basic table rendering
HTML part (assuming you have introduced Layui's CSS and JS files):
<table lay-filter="test"></table>
JavaScript part (using):
('table', function(){ var table = ; //Execute a table instance ({ elem: '#demo' ,cols: [[ //Title bar {field: 'id', title: 'ID', width:80, sort: true, fixed: 'left'} ,{field: 'username', title: 'username', width:80} ,{field: 'sex', title: 'gender', width:80, sort: true} ,{field: 'city', title: 'City', width:80} ,{field: 'sign', title: 'sign', width: 180} ,{field: 'experience', title: 'integral', width: 80, sort: true} ,{field: 'score', title: 'score', width: 80, sort: true} ,{field: 'classify', title: 'Profession', width: 80} ,{field: 'wealth', title: 'wealth', width: 135, sort: true} ]] ,data: [{ "id": "10000", "username": "Du Fu", "sex": "male", "city": "Hangzhou", "sign": "Life is like a practice", "experience": "254", "score": "80", "classify": "poet", "wealth": "100,000" // ... Other data }] }); });
Example 2: Usingtemplet
Custom column content
In this example, we will add a custom display format for the Wealth column (for example, add a currency symbol):
({ elem: '#demo' ,cols: [[ // ... Other column configuration {field: 'wealth', title: 'wealth', width: 135, sort: true, templet: function(d){ return '¥' + ; // Assume it is a numeric value or a string that can be spliced directly }} // ... Other column configuration ]] // ...Other configurations such as data or url});
Example 3: Asynchronous loading of data
If your data is not static, but needs to be retrieved from the server through AJAX calls, you can seturl
Attributes rather thandata
Attributes:
({ elem: '#demo' ,cols: [[ //Title bar {field: 'id', title: 'ID', width:80, sort: true} // ... Other column configuration ]] ,url: '/api/data' // Your data interface ,page: true //Open the paging ,limit: 10 //The default number of displayed per page ,limits: [5, 7, 10, 20, 30, 50, 100] //The number of options displayed per page ,id: 'testReload' //Specify a unique rendering identifier, generally used for table overloading});
In the asynchronous loading example above, you need to make sure/api/data
This URL can return the data format expected in the Layui table, usually a containingcode
、msg
anddata
(orcount
andlist
JSON objects with fields such as ).data
The field should be an array containing rows of data, and each row of data should be combined withcols
Infield
Match.
The data format returned by the backend is different from the default format of the layui:
If the data returned by the backend does not match the format expected by the Layui table component, you will need to take some steps to ensure that the data can be parsed and rendered correctly. Here are some possible solutions:
1. Modify the backend data format
The most direct way is to modify the data return format of the backend interface to match the requirements of the Layui table component. This usually involves tweaking the serialization logic of the database query or API to ensure that the returned JSON object containscode
、msg
anddata
etc., anddata
A field is an array of multiple objects.
2. UseparseData
Callback function
If you cannot modify the backend data format, you can use Layui'sUse in the method
parseData
Callback function to parse raw data. This callback function allows you to customize the parsing logic based on the structure of the original data and return the parsed data in the format expected by the Layui table component.
For example, if the data returned by the backend is like this:
{ "status": 0, "message": "success", "items": [ { /* Data item 1 */ }, { /* Data item 2 */ }, // ... ] }
You can configure it like thisparseData
Callback function:
({ elem: '#demo', url: '/api/your-data-endpoint', cols: [[ // ...Table header configuration ]], parseData: function(res) { // res is the original data returned by the backend // Here we parse the original data into the format expected by the Layui table return { "code": , // Map the status field in the original data to code "msg": , // Map the message field in the original data to msg "count": , // Assume that the length of the items array is the total number of records (if paging is supported, more accurate calculations are required here) "data": // Map the items array in the original data to data }; } // ... Other configurations});
3. Consider paging and sorting
If the backend interface supports pagination and sorting, and these parameters do not match the default parameters of the Layui table component, you also need toPassed in the method
page
、limit
、limits
etc. are configured, and the paging and sorting information is passed to the backend through URL parameters or request headers.
4. Error handling and debugging
In configuration and useWhen doing this, make sure you have considered error handling and debugging. You can use the browser's developer tools to view the details of AJAX requests, including the request URL, request header, request body, response header, and response body. This helps you diagnose the problem and adjust the configuration of the front-end or back-end.
5. Follow best practices
- Ensure that the documentation for the backend interface is up to date and clearly describes the format and possible status codes of the returned data.
- Use appropriate error handling and user feedback mechanisms on the front end to provide clear instructions to the user when the data does not load correctly.
- Optimize performance, especially when processing large amounts of data. Consider using techniques such as paging, lazy loading, or infinite scrolling to reduce the amount of data loaded at one time.
- Follow the official documentation and best practice guides for Layui Form Components to ensure your implementation is robust and easy to maintain.
This is the end of this article about the use of Layui. For more related content on Layui, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!