小程序中上拉刷新下拉加载更多

    科技2025-06-20  15

    wxml:

    <view> <include src="./searchbar.wxml" /> <block wx:for="{{list}}" wx:key="{{item.id}}"> <navigator url="/pages/detail/detail?id={{item.id}}" class="cell"> <view class="imageView"> <image src="{{item.images[0]}}"></image> </view> <view class="meta"> <text class="name">{{item.name}}</text> <text class="time">{{item.phone}}</text> <text class="time">{{item.address}}</text> <text class="time">{{item.businessHours}}</text> </view> <view class="score"> {{item.score || 0}} </view> </navigator> </block> <view> <block wx:if="{{hasMore}}"> <view class="loadMore loading">正在加载中...</view> </block> <block wx:else> <view class="loadMore"> <text>没有更多啦</text> </view> </block> </view> </view>

    js:

    import axios from '../../utils/http.js' Page({ /** * 页面的初始数据 */ data: { cate_id:null, //分类id pageIndex:0,// 页码 pageSize:10, //页容量 //keyword:'', //关键字 空串代表的是全部 hasMore:true,//是否还有更多 list:[], // 店铺列表 inputShowed: false, // input是否显示 inputVal: "" // input中输入的值 }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { // 动态设置导航栏的标题 wx.setNavigationBarTitle({ title: options.name, }) // 这个地方我也没有使用 setData this.data.cate_id = options.cate_id // 加载第一页的数据 this.loadData() }, /** * 这个方法,既给第一次加载数据用,也给上拉加载 & 下拉刷新使用 */ loadData(){ // 判断,如果已经没有数据了 if (!this.data.hasMore) return // 这里并没有使用 setData this.data.pageIndex++ // 发送请求 const url = `categories/${this.data.cate_id}/shops?_page=${this.data.pageIndex}&_limit=${this.data.pageSize}&q=${this.data.inputVal}` axios.get(url).then(res => { // 停止下拉刷新 wx.stopPullDownRefresh() // 把已有的数据和新返回的数据,拼接起来 const newArray = [...this.data.list, ...res.data] const hasMore = newArray.length < parseInt(res.header["X-Total-Count"]) this.setData({ list: newArray, hasMore }) }) }, /** 搜索相关的方法 start */ showInput: function () { this.setData({ inputShowed: true }); }, hideInput: function () { this.setData({ inputVal: "", inputShowed: false }); }, clearInput: function () { this.setData({ inputVal: "" },() => { this.getLastValue() }); }, inputTyping: function (e) { this.setData({ inputVal: e.detail.value }); }, // 获取最终要进行搜索的值 getLastValue() { // console.log(this.data.inputVal) // 重置 this.data.pageIndex = 0 this.setData({ list: [], hasMore: true }, () => { // 因为 setData 是异步的,必须保证setData设置完毕之后,再去调用loadData this.loadData() }) }, /** 搜索相关的方法 end */ /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { // console.log("111111") // 重置 this.data.pageIndex = 0 this.setData({ list:[], hasMore:true },() => { // 因为 setData 是异步的,必须保证setData设置完毕之后,再去调用loadData this.loadData() }) }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { this.loadData() }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
    Processed: 0.014, SQL: 8