WeChat applet to obtain background dynamic data Gird table layout display: grid

WeChat applet to obtain background dynamic data Gird table layout display: grid

The flex layout and grid layout are commonly used in work, because I am not very familiar with grid layout, this time I mainly want to simulate the dynamic data of the background to dynamically set the table layout. It is a simple attempt. After all, it was not useful before. Over. share.

If you are unfamiliar with CSS grid layout, please read this article, the introduction is very detailed: CSS Grid Layout Complete Guide (Illustrated Grid Detailed Tutorial)

(1) Achieving effect

The effect achieved by the display:table layout of the back-end dynamic data table layout of the WeChat applet in my previous article is very similar, but I am going to write this article because this method optimizes a lot of code and is worth learning.

(2) Realization process

1. The js setting is very simple. The background data format obtained is simulated through the array object format:

Page({
  data: {
    tableData: [{//
      id: 0,
      name: 'table-th-cell'
    },
    {
      id: 1,
      name: 'table-th-cell'
    },
    {
      id: 2,
      name: 'table-th-cell'
    },
    {
      id: 3,
      name: 'table-tr-cell'
    },
    {
      id: 4,
      name: 'table-tr-cell'
    },
    {
      id: 5,
      name: 'table-tr-cell'
    },
    {
      id: 6,
      name: 'table-tr-cell'
    },
    {
      id: 7,
      name: 'table-tr-cell'
    },
    {
      id: 8,
      name: 'table-tr-cell'
    },

    ],
  },
  onLoad: function () {
  },
}) 

2. Setting wxml is also some common layout format:

<view class="table">

  <block wx:for='{{tableData}}' wx:key='*this'>
    <view class='table-th' wx:if='{{index<3}}'>{{item.name}}</view>
    <view class='table-td' wx:else>{{item.name}}</view>
  </block>
</view> 

3. Wxss setting, mainly through the parent container to set the block-level grid, and then set the parent container's column and row size, the unit of fr is equally divided column space; when there is extra data set, the default row height when automatically adding new rows is 200rpx; set the size of the grid line; for sub-elements, you can customize the style content according to your own:

.table {
  display: grid;
  width: 100%;
  overflow-x: hidden;
 /*   fr */
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 200rpx 200rpx;
 /*  200rpx */
  grid-auto-rows: 200rpx;
 /*   */
  grid-gap: 10rpx;
}

.table-th {
  font-weight: bold;
  background-color: #888;
  display: flex;
  justify-content: center;
  align-items: center;
}

.table-td {
  background-color: #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
}
 

In general, compared display:tableto the layout of the grid simplifies a lot of code, a little easier.