小程序(加载数据,下拉加载更多,上拉刷新)

136 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第30天,点击查看活动详情

页面布局:

 <view class="container" wx:for="{{subject}}" wx:key="index" >
  <view class="box1">{{item.Title}}</view>
  <view class="box2">
   <view class="box_a">{{item.Section.Name}}</view>
   <view class="box_b">{{item.Createtime}}</view>
 </view>
</view>

页面样式:

.container {
 width: 100vw;
  border-bottom: 3px solid #ccc;
 height: 60px;
 line-height: 30px;
}

   .box1 {
  font-weight: bold;
 }

 .box2 {
 display: flex;
 justify-content: space-between;
 }
 
 

js内容:

                                  Page({

       
      data: {

pageIndex页码:默认一页10条数据

  pageIndex: 1,

定义一个空数组接收后台数据

  subject: []
           },
    async onrejects() {
    let subject = await wx.$request("Subject/GetSubjects", {
      pageIndex: this.data.pageIndex
      })

subject为当前获取的10条数据 image.png

subject.forEach(r => {


  r.Createtime = wx.getminiDate(r.Createtime)
  

r.Createtime时间

wx.getminiDate(r.Createtime)调用函数把时间戳化成正常时间 image.png }) 如果subject长度=0代表没有数据了,就会提示

if (subject.length == 0) {
wx.$msg调用封装的方法

  wx.$msg("没有消息了!")
  return
}
下拉的时候会根据页码把新的数据加到subject里,这样数据就不会只有10this.data.subject.push(...subject)
this.setData({
  subject: this.data.subject
})
  },

下拉触底

  onReachBottom() {
  页码会增加
   ++this.data.pageIndex
   this.onrejects()
  },
  

image.png 生命周期函数--监听页面加载

  onLoad(options) {
    this.onrejects()
  },

上拉刷新

  onPullDownRefresh() {
  this.data.pageIndex = 1  //页码回到第一页
   this.data.subject = []  //清空subject
this.onrejects()    
setTimeout(() => {
1.5秒关闭上拉刷新
  wx.stopPullDownRefresh()
}, 1500)
 }
 }) 

刷新数据

需要在当前json里面写内容 下拉刷新enablePullDownRefresh的支持(false不支持刷新)

  "enablePullDownRefresh": true,
      "backgroundColor": "#369",
    "backgroundTextStyle": "dark"

image.png

封装方法,每个文件夹里的js都可以调用

            // 时间
let getminiDate = (time) => {
  let date = new Date(parseInt(time))
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  month = month < 10 ? "0" + month : month
let day = date.getDate()
 day = day < 10 ? "0" + day : day
  return [year, month, day].join("-")
}

 let $confirm=(title)=>{
  return new Promise(res=>{
 wx.showModal({
 title,
 success:(confirm=>{
   if(confirm){
     res()
   }
 })
})
 })
  }

  // 提示消息
 let  $msg=(title)=>{
 return wx.showToast({
title
 })
  }
wx.getminiDate=getminiDate
wx.$confirm=$confirm
wx.$msg=$msg
 

获取数据

  function $request(url, data, method = "GET") {
   return new Promise((res, req) => {
// 加载loading
// wx.showModal({
//   title: '数据加载中'
// })
// 发生请求
wx.request({
  url:"https://bingjs.com:8002/"+url,
  data,
  method,
  success: ({
    data
  }) => {
    res(data)
    
  },
  // 请求完成的回调
  // complete: () => {
  //   // 关闭loading
  //   wx.hideLoading()
  // }
})
})
  }
// 导出
module.exports={$request}
wx.$request=$request