Home >Web Front-end >Layui Tutorial >How do I use Layui's table component for displaying data?

How do I use Layui's table component for displaying data?

Emily Anne Brown
Emily Anne BrownOriginal
2025-03-12 13:33:18135browse

How do I use Layui's table component for displaying data?

Layui's table component provides a simple yet powerful way to display data in a tabular format. The core of using it involves setting up the table structure using HTML and then populating it with data using JavaScript. Here's a breakdown:

First, you need to include the Layui CSS and JavaScript files in your HTML:

<code class="html"><link rel="stylesheet" href="layui/css/layui.css">
<script src="layui/layui.js"></script></code>

Next, you create a table element in your HTML, which will serve as the container for your table. This element needs an id attribute for Layui to target it. You can also optionally include some basic table structure:

<code class="html"><table id="demo" lay-filter="test"></table></code>

The lay-filter attribute is crucial; it's used to identify the table instance for later manipulation.

Finally, you use JavaScript to render the table data using layui.table.render(). This function takes an object as its argument, specifying various options like the element ID (elem), data (data), columns (cols), and other configurations. Here's an example:

<code class="javascript">layui.use('table', function(){
  var table = layui.table;
  table.render({
    elem: '#demo'
    ,cols: [[ //标题栏
      {field: 'id', title: 'ID', width:80, sort: true}
      ,{field: 'username', title: '用户名', width:80}
      ,{field: 'email', title: '邮箱', width:120}
      ,{field: 'sex', title: '性别', width:80}
      ,{field: 'city', title: '城市', width:80}
      ,{field: 'sign', title: '签名', width:170}
    ]]
    ,data: [ //假设数据
      {'id':'1','username':'张三','email':'zhangsan@gmail.com','sex':'男','city':'西安','sign':'hello'}
      ,{'id':'2','username':'李四','email':'lisi@gmail.com','sex':'女','city':'北京','sign':'hello world'}
    ]
    ,page: true //开启分页
  });
});</code>

This code renders a table with the specified columns and data. Remember to replace the sample data with your actual data. The page: true option enables pagination (explained further below).

Can I customize the columns in Layui's table component?

Yes, Layui's table component offers extensive column customization. You can control various aspects of each column, including:

  • field: The data key corresponding to the column. This is how Layui maps data to columns.
  • title: The column header text.
  • width: The column width (in pixels or percentage).
  • sort: Enables sorting for this column (true/false).
  • templet: A function or string template to customize how data is displayed in the cell. This allows for complex formatting, including using icons, links, or other HTML elements. For example, you could use a template to display a user's status with a colored icon.
  • toolbar: Allows you to add custom buttons or actions within each row's cell. This is useful for creating edit, delete, or other row-specific operations.
  • edit: Enables in-place cell editing. This allows users to directly modify data within the table.
  • type: Allows you to specify different column types like 'checkbox' to add checkboxes to each row.

Here's an example demonstrating templet and toolbar:

<code class="javascript">cols: [[
  {field: 'status', title: 'Status', templet: function(d){
    return d.status === 1 ? '<span style="color:green;">Active</span>' : '<span style="color:red;">Inactive</span>';
  }}
  ,{field: 'actions', title: 'Actions', toolbar: '#barDemo'}
]]</code>

This adds a status column with conditional coloring and an actions column with custom buttons defined in a template with the id barDemo.

How do I handle pagination with Layui's table component?

Layui's table component simplifies pagination. To enable pagination, simply set the page option to true in the table.render() function:

<code class="javascript">table.render({
  // ... other options ...
  page: true
});</code>

This will automatically add pagination controls to the bottom of the table. Layui handles the fetching and display of data for each page. You can further customize pagination by specifying additional options:

  • limit: The number of rows per page.
  • limits: An array of options for the number of rows per page that users can select.
  • layout: Controls which pagination elements are displayed (e.g., 'count', 'prev', 'page', 'next', 'limit', 'skip').
  • curr: Specifies the current page number. Useful when loading a specific page.

For larger datasets, you'll typically want to fetch data from your backend API in chunks based on the current page number and limit. This is covered in the next section.

How can I integrate Layui's table component with my backend API?

Integrating Layui's table with a backend API involves fetching data using AJAX (typically with jQuery's $.ajax() or the browser's built-in fetch() API) and then passing that data to the table.render() function. You'll usually need to adjust your API calls based on the current page and limit.

Here's an example using fetch():

<code class="javascript">layui.use('table', function(){
  var table = layui.table;
  let currentPage = 1;
  let pageSize = 10;

  function fetchData(page, limit) {
    return fetch(`/api/data?page=${page}&limit=${limit}`)
      .then(response => response.json())
      .then(data => {
        return {
          data: data.items, // Assuming your API returns an object with 'items' property
          count: data.totalCount // Assuming your API returns total count
        };
      });
  }

  fetchData(currentPage, pageSize).then(data => {
    table.render({
      elem: '#demo',
      cols: [[ /* ... your columns ... */ ]],
      data: data.data,
      page: {
        curr: currentPage,
        limit: pageSize,
        count: data.count
      }
    });
  });
});
</code>

This code fetches data from /api/data, passing the page number and limit as query parameters. The response is then used to render the table. Remember to adjust the API endpoint and data structure to match your backend. You would also typically add event listeners to handle pagination changes and update currentPage accordingly, refetching data when the page changes. Error handling and loading indicators are also important considerations for a production-ready implementation.

The above is the detailed content of How do I use Layui's table component for displaying data?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn