微信小程序 下拉刷新/上拉加载更多 (上拉加载更多怎么实现)

实现原理:

  1. 下拉刷新:由于小程序数据是实时渲染的。我们把data{}内的数据清空重新加载即可实现下拉刷新。
  2. 上拉加载更多(页面上拉触底事件):新获取的数据追加到data{}内的原数据即可。由于小程序数据是实时渲染,小程序在保持原数据显示不变的基础上,自动追加渲染显示新数据。
注意(小程序官方有说明):
  1. 上拉加载更多 不要用scroll-view,用普通的view即可。
  2. 下拉刷新需要在 当前页面.json 里配置
{
   "enablePullDownRefresh": true 
}
  1. page()属性里有两个属性是关于页面下拉刷新 和 上拉加载更多的:
onPullDownRefresh Function 页面相关事件处理函数–监听用户下拉动作
onReachBottom Function 页面上拉触底事件的处理函数
文章列表页的demo代码:

index.wxml

<!--pages/home/index.wxml-->
<view class='container' wx:for="{{articles}}">
   <!-- 文章列表  -->
   <view  bindtap="onArticle"  data-aid="{{item.id}}">
      <view class='a-title '>{{item.title}}</view>
      <image class='a-thumb' src="{{item.thumb}}" mode="widthFix"></image> 
   </view>
</view>

index.js

**//pages/home/index.js
var page=0;//分页标识,第几次下拉,用户传给后台获取新的下拉数据
Page({
   data: {  
      articles: [],//数组
   },
   // 页面加载
   onLoad: function () {
      this.clearCache();//清本页缓存
      this.getArticles(0);//第一次加载数据
   },
   // 下拉刷新
   onPullDownRefresh: function () {
     this.clearCache();
     this.getArticles(0);//第一次加载数据
   },
   // 页面上拉触底事件(上拉加载更多)
   onReachBottom: function () {
      this.getArticles(page);//后台获取新数据并追加渲染
   },
   // 清缓存
   clearCache:function(){
      page = 0;//分页标识归零
      this.setData({
         articles: [] //数组清空
      }); 
   },
    // 点击跳转详情页
   onArticle:function(){
      //业务逻辑
   },
   /**
    * 获取
    * @param {int} pg  分页标识 默认0
    */
   getArticles: function (pg) {
      //设置默认值
      pg = pg ? pg : 0;
      var that = this;
      var apiUrl = 'http://www.zhipur.com/Api/Article/getArticles';//地址
      var postData = {
         page: pg,//分页标识
         app_version: 1.2,//当前版本,后台根据版本不同给出不同的数据格式
      }
      wx.request({
         url: apiUrl,
         data: postData,
         method: 'POST',
         header: { 'content-type': 'application/x-www-form-urlencoded' },
         success: function (res) { 
            if (res.data.status == 1) {//成功
               var tmpArr = that.data.articles;
               // 这一步实现了上拉加载更多
               tmpArr.push.apply(tmpArr,res.data.data);
               that.setData({
                  articles: tmpArr
               })
               page++;
            } else {//失败
               console.log(res.data.info);
            }
         },
         fail: function (e) {
            console.log(e);
         }
      })        
   },
})**
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值