小程序中上拉加载、下拉刷新、回到顶部以及详情页的实现

home.wxml

<!-- 在微信中传参是通过给组件加属性 -->
<view >
  <view wx:for="{{list}}" class="home" wx:key="_id" bindtap="toDetail" id="{{item._id}}">
    <view class="home-text" >
    <!-- 实现图片懒加载  lazy-load="true"就可以实现-->
      <image src="{{item.imgUrl}}" class="home-img" mode="aspectFit" lazy-load="true"></image>
      {{item.title}}
    </view>
    <view class="home-price">
      <view>¥{{item.pricce}}元</view>
      <view class="home-add">+</view>
    </view>
  </view>
  <view class="home-top" bindtap="goTop">返回顶部</view>
</view>

home.js

// 定义数据库实例
const db = wx.cloud.database()
Page({
  data: {
    list: []
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.page = 0
    this.getList(true)
    console.log(this)
    // 以下代码是全部获取数据
    // wx.showLoading({
    //   title: '加载中',
    // })
    // db.collection('emall').get({
    //   success: res => {
    //     console.log(res)
    //     this.setData({
    //       list: res.data
    //     })
    //     wx.hideLoading()
    //   }
    // })
  },
 //  跳转到详情页
  toDetail(e) {
    const id = e.currentTarget.id
    console.log(id)
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + id,
    })
  },
/**
   * 页面相关事件处理函数--监听用户下拉动作,下拉刷新
   */
  onPullDownRefresh: function () {
    this.getList(true)
  },

  /**
   * 页面上拉触底事件的处理函数,上拉加载
   */
  onReachBottom: function () {
    this.page += 1
    this.getList()
  },
  // 
  getList (isInit) {
    const PAGE = 3
    wx.showLoading({
      title: '加载中...',
    })
    //  skip从当前数据跳过,重新加载三条
    db.collection('emall').skip(this.page * PAGE).limit(PAGE).get({
      success: res => {
        console.log(res)
        if (isInit) {
          this.setData({
            list: res.data
          })
          wx.stopPullDownRefresh()
        } else {
          // 下拉刷新,不直接覆盖而是累加
          this.setData({
            list: this.data.list.concat(res.data)
          })
        }
        wx.hideLoading()
      }
    })
  },
  // 滚动到顶部
  // onPageScroll: function (e) {
  //   console.log(e)
  //   // 此处的e代表scrollTop

  // },
  goTop: function (e) {
    console.log(e)
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0,
      })
    }
  }

home.wxss

 /* pages/home/home.wxss */
.home {
  display: flex;
  justify-content: space-between;
  margin-bottom: 80rpx;
  border-bottom: 2rpx solid #ccc;
  padding-bottom: 20rpx;
  height: 1000rpx;
}
.home-img {
  width: 200rpx;
  height: 200rpx;
}
.home-text {
  display: flex;
}
.home-price {
  margin-right:40rpx;
}
.home-add {
  width: 40rpx;
  height: 40rpx;
  background-color: #ff0000;
  text-align: center;
  margin-top: 80rpx;
}
.home-top {
  width: 80rpx;
  height: 100rpx;
  border: 2rpx solid #ddd;
  position: fixed;
  bottom: 60rpx;
  right: 40rpx;
  background-color: #232333;
  color: #fff;
  text-align: center;
  line-height: 50rpx;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。