uni-app實現上拉載入

青茶360發表於2024-05-13

參考文件程式碼:

 1 <template>
 2   <view>
 3     <!-- 省略其他內容 -->
 4     <view v-for="item in dataList" :key="item.id">{{ item.title }}</view>
 5   </view>
 6 </template>
 7 
 8 <script>
 9   export default {
10     data () {
11       return {
12         dataList: [], // 儲存資料列表
13         pageNum: 1, // 當前頁數
14       }
15     },
16     onReachBottom () {
17       this.requestNextPageData()
18     },
19     methods: {
20       async requestNextPageData () {
21         const res = await uni.request({
22           url: 'your-api-url',
23           data: {
24             pageNum: this.pageNum,
25           },
26         })
27         if (res.statusCode === 200) {
28           const nextDataList = res.data // 假設介面返回資料格式為 { data: [...] }
29           if (nextDataList.length > 0) {
30             this.dataList = this.dataList.concat(nextDataList)
31             this.pageNum++
32           } else {
33             uni.showToast({
34               title: '沒有更多了',
35               icon: 'none',
36             })
37           }
38         } else {
39           uni.showToast({
40             title: '請求失敗,請重試',
41             icon: 'none',
42           })
43         }
44       },
45     },
46   }
47 </script>

自己的程式碼:

//上拉載入
        onReachBottom() {
            if (!this.pullUpOn) {
                return;
            }

            //this.loadPosts(false);
        },
// 點選欄目切換當前頁時改變樣式
            swichNav(e) {
                let cur = e.currentTarget.dataset.current;

                if (this.currentTab == cur) {
                    return false;
                }

                this.currentTab = cur;
                // this.posts = [];
                this.loadPosts(true);
            },
//根據id獲取某個分類下文章
            loadPosts(refresh) {
                this.loadding = true;
                Rest.get(Api.JIANGQIE_POSTS_CATEGORY+'&catid='+this.tabbar[this.currentTab]['id']+'&pagesize=50&more=1', {
                    //'offset': refresh ? 0 : this.posts.length,
                    //'sort': this.sorts[this.currentTab]
                }).then(res => {                    
                    this.loaded = true;
                    this.loadding = false;
                    this.posts = (refresh ? res.data : this.posts.concat(res.data));
                    //this.pullUpOn = (res.data.length >= Constants.JQ_PER_PAGE_COUNT);
                    //this.pageNum++;
                    console.log('欄目id',this.tabbar[this.currentTab]['id']);
                    console.log('欄目id文章',res.data);
                });
            }
<!-- 頂部欄目 -->
        <scroll-view scroll-x scroll-with-animation class="tab-view" :scroll-left="0">
            <view v-for="(item, index) in tabbar" :key="index" class="tab-bar-item"
                :class="(currentTab==index ? 'active' : '')" :data-current="index"
                @tap.stop="swichNav">
                <text class="tab-bar-title">{{item.name}}</text>
            </view>
        </scroll-view>

相關文章