Simple and efficient WeChat applet paginator packaging practice

Preface

In today's mobile application development, WeChat applet has become a popular platform. However, as the complexity of the application increases, data management and loading become an issue. This article will explore a key concept in WeChat mini programs: the encapsulated pager, which is one of the indispensable tools for improving mini program performance and user experience. By deeply understanding how the paginator works and how to package and use it correctly, you will be able to better manage and load data, thereby bringing better performance and user experience to your applet.


achieve effect

Insert image description here


Encapsulate public methods

wxmldocument

First, in the view layer ( WXML), a custom component containing paging-related elements is created, including the display of the total number of data items, the drop-down box showing the number of items per page, the display of the current page number, the previous page and the next page. button and the input box to go to the page number.

<view class="mainBox">
  <view class="paginationBox">
    <view class="totalBox">共 {
   
   {total}} 条</view>
    <view class="selectPageBox">
      <picker bindchange="handlePageSizeChange" value="{
     
     {pageSizeIndex}}" range="{
     
     {pageSizes}}">
        <view>{
   
   {pageSizes[pageSizeIndex]}}条/页</view>
      </picker>
    </view>
    <view class="contantBox">
      <view style="color:{ 
        { 
        pageNum<=1 ? 'rgb(194,201,213)' : 'rgb(25, 137, 250)'}}" class="updownPageBox" bindtap="prevPage">
        <van-icon name="arrow-left" />
      </view>
      <view class="pageBox">{
   
   {pageNum}}</view>
      <view style="color:{ 
        { 
        pageNum >= (total / pageSize) ? 'rgb(194,201,213)' : 'rgb(25, 137, 250)'}}" class="updownPageBox" bindtap="nextPage">
        <van-icon name="arrow" />
      </view>
    </view>
    <view class="intBox">
      <text>前往</text>
      <input class="intConBox" bindconfirm="handlePageConfirm" type="number" />
      <text></text>
    </view>
  </view>
</view>

jsdocument

  • propertiesThree properties are defined in the component's properties ( ): total, pageSize, pageNum, which are used to control paging-related data. Among them, totalrepresents the total number of data items, pageSizerepresents the number of items displayed on each page, and pageNumrepresents the current page number. At the same time, pageNuman observer function is defined in the attribute to pageNumupdate the data when the attribute changes pageNum;
  • Defines datasome variables in data ( ), including the number of items displayed per page option pageSizesand the number of items displayed per page selected by default pageSizeIndex;
  • Some methods are defined in methodsto implement the paging function:
    • prevPageMethod: used to click the previous page button, reduce pageNum, but make sure pageNumit is greater than 1, trigger a custom event pageChangeand pass the current page number information;
    • nextPageMethod: used to click the next page button, increase pageNum, but make sure pageNumit is less than the maximum number of pages, trigger a custom event pageChangeand pass the current page number information;
    • handlePageSizeChangeMethod: Use the drop-down box to select the number of items displayed on each page, update pageSizeand pageSizeIndex, trigger a custom event pageSizeChangeand pass the information on the number of items displayed on each page;
    • handlePageConfirmMethod: Used for the confirmation operation of the page number input box, obtain the input page number and convert it into an integer, ensure that the input page number is within the valid range, then update pageNum, trigger a custom event pageChangeand pass the current page number information;
    • Custom events pageChangeand pageSizeChangecan be listened in the parent component using this component to perform corresponding logical operations when the paging information changes.
Component({
    
    
  properties: {
    
    
    total: {
    
     // 总数据条数
      type: Number, // 数据类型为数字
      value: 0 // 默认值为0
    },
    pageSize: {
    
     // 每页显示条数
      type: Number, // 数据类型为数字
      value: 10 // 默认值为10
    },
    pageNum: {
    
     // 当前页码
      type: Number, // 数据类型为数字
      value: 1, // 默认值为1
      observer(newVal) {
    
     // 当pageNum属性变化时触发的观察者函数
        this.setData({
    
    
          pageNum: newVal // 更新数据中的pageNum
        });
      }
    }
  },
  data: {
    
    
    pageSizes: [5, 10, 15, 20], // 每页显示条数选项
    pageSizeIndex: 1, // 默认选中的每页显示条数
  },
  methods: {
    
    
    // 上一页
    prevPage() {
    
    
      if (this.data.pageNum > 1) {
    
     // 如果当前页码大于1
        this.setData({
    
    
          pageNum: this.data.pageNum - 1 // 减小pageNum
        });
        this.triggerEvent('pageChange', {
    
     // 触发名为'pageChange'的自定义事件,传递当前页码信息
          page: this.data.pageNum
        });
      } else {
    
    
        wx.showToast({
    
    
          title: '已经是第一页',
          icon: 'none'
        });
      }
    },
    // 下一页
    nextPage() {
    
    
      const maxPage = Math.ceil(this.data.total / this.data.pageSize); // 计算最大页数
      if (this.data.pageNum < maxPage) {
    
     // 如果当前页码小于最大页数
        this.setData({
    
    
          pageNum: this.data.pageNum + 1 // 增加pageNum
        });
        this.triggerEvent('pageChange', {
    
     // 触发名为'pageChange'的自定义事件,传递当前页码信息
          page: this.data.pageNum
        });
      } else {
    
    
        wx.showToast({
    
    
          title: '已经是最后一页',
          icon: 'none'
        });
      }
    },

    // 每页显示条数下拉框
    handlePageSizeChange(event) {
    
    
      const index = event.detail.value; // 获取选择的索引
      const pageSize = this.data.pageSizes[index]; // 获取对应索引的每页显示条数
      this.setData({
    
    
        pageSize, // 更新pageSize
        pageSizeIndex: index, // 更新pageSizeIndex
      });
      this.triggerEvent('pageSizeChange', {
    
     // 触发名为'pageSizeChange'的自定义事件,传递每页显示条数信息
        pageSize
      });
    },
    // 页码输入框
    handlePageConfirm(event) {
    
    
      const inputValue = event.detail.value.trim(); // 获取去掉前后空格的输入值
      if (inputValue === '') {
    
    
        // 如果输入值为空,则不执行查询操作
        return;
      }
      const page = parseInt(inputValue); // 获取输入的页码并转换为整数
      const maxPage = Math.ceil(this.data.total / this.data.pageSize); // 计算最大页数
      if (page >= 1 && page <= maxPage) {
    
     // 如果输入的页码有效
        this.setData({
    
    
          pageNum: page // 更新pageNum
        });
        this.triggerEvent('pageChange', {
    
     // 触发名为'pageChange'的自定义事件,传递当前页码信息
          page
        });
      } else {
    
    
        wx.showToast({
    
    
          title: '请输入有效页数',
          icon: 'none'
        });
      }
    }

  }
});

wxssdocument

.paginationBox {
    
    
  margin-top: 20rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.totalBox {
    
    
  color: #606266;
  height: 48rpx;
  line-height: 48rpx;
}

.selectPageBox {
    
    
  border: 2rpx solid #dcdfe6;
  margin: 0rpx 14rpx;
  color: #606266;
  padding: 0rpx 18rpx;
  text-align: center;
  height: 44rpx;
  line-height: 44rpx;
  border-radius: 4rpx;
}

.contantBox {
    
    
  display: flex;
}

.updownPageBox,
.pageBox {
    
    
  padding: 0rpx 14rpx;
  color: rgb(25, 137, 250);
  background-color: rgb(244, 244, 245);
  height: 48rpx;
  line-height: 48rpx;
  border-radius: 4rpx;
}

.pageBox {
    
    
  margin: 0rpx 10rpx;
}

.intBox {
    
    
  margin-left: 14rpx;
  color: #606266;
  display: flex;
  align-items: center;
}

.intBox input {
    
    
  height: 44rpx;
  line-height: 44rpx;
  min-height: 44rpx;
}

.intConBox {
    
    
  border: 2rpx solid #dcdfe6;
  border-radius: 4rpx;
  width: 60rpx;
  text-align: center;
  margin: 0rpx 6rpx;
}

app.jsonFile global reference

"usingComponents": {
    
    
    "pagination": "./components/pagination/index"
},

Use any file

wxmldocument

<view class="tableBox">
    <scroll-view scroll-x>
        <view class="table">
            <view class="tableRow">
                <text class="tableNavBox">Header 1</text>
                <text class="tableNavBox">Header 2</text>
                <text class="tableNavBox">Header 3</text>
            </view>
            <view class="tableRow" wx:for="{
     
     {list}}" wx:key="index">
                <text class="tableCellBox">{
   
   {item.ffzt}}</text>
                <text class="tableCellBox">{
   
   {item.fdjccrq}}</text>
                <text class="tableCellBox">{
   
   {item.gl}}</text>
            </view>
        </view>
    </scroll-view>
    <!-- 分页组件 -->
    <view>
        <pagination total="{
     
     {total}}" pageSize="{
     
     {pageSize}}" currentPage="{
     
     {currentPage}}" bind:pageChange="handlePageChange" bind:pageSizeChange="handlePageSizeChange">
        </pagination>
    </view>
</view>

jsdocument

var app = getApp(); // 获取小程序应用实例
Page({
    
    
    data: {
    
    
        list: [], // 存储数据列表
        pageNum: 1, // 当前页码
        total: 0, // 数据总数
        pageSize: 10, // 每页显示条数
    },
    onLoad: function () {
    
    
        this.tableOn(); // 在页面加载时调用tableOn函数
    },
    tableOn() {
    
    
        let that = this; // 缓存this,以在回调函数中使用
        // 发起网络请求获取数据
        wx.request({
    
    
            url: app.API_URL + 'yourUrl', // 请求的URL
            data: {
    
    
                rows: {
    
    
                    pageNum: that.data.pageNum, // 当前页码
                    pageSize: that.data.pageSize, // 每页显示条数
                },
            },
            success: function (res) {
    
    
                that.setData({
    
    
                    list: res.data.list, // 更新数据列表
                    total: res.data.pagejx.areaNum, // 更新数据总数
                });
            },
        });
    },
    // 处理分页组件页码变化事件
    handlePageChange(event) {
    
    
        this.setData({
    
    
            pageNum: event.detail.page, // 更新当前页码
        });
        this.tableOn(); // 重新加载数据
    },
    // 处理分页组件每页显示条数变化事件
    handlePageSizeChange(event) {
    
    
        this.setData({
    
    
            pageNum: 1, // 重置页码为1
            pageSize: event.detail.pageSize, // 更新每页显示条数
        });
        this.tableOn(); // 重新加载数据
    },
});

related suggestion

⭐Use vue to encapsulate the paginator to make your page simple yet elegant

Guess you like

Origin blog.csdn.net/Shids_/article/details/133709019