vue 上滑加載更多


移動端網頁的上滑加載更多,其實就是滑動+分頁的實現。

 

 

<template>
    <div>
        <p class="footer-text">--{{footerText}}--</p>
        <p class="loading" v-show="loading"></p>
    </div>
</template>
<script>
    import $ from 'jquery'
    export default {
        data(){
            return{
                serverData:[],//接受服務器的數據,
                page:1,
                footerText:'上滑加載更多',
                loading:false//loading的開關
            }
        },
        created(){
            this.getServerData(this.page);
            this.listenScroll();
        },
        beforeDestroy(){
            $(window).unbind('scroll');
        },
        methods:{
            getServerData(){
                //參數只有page,項目需要可以添加
                //項目中的ajax方式可能跟這個不一樣,沒關系,思路是相同的。
                const num = 3;//每一頁接受多少條數據
                this.$api.get('url',{page:this.page},res=>{
                    this.loading = false;
                    this.serverData = res.data;//接受數據
                    if(res.data.length<num){
                        this.footerText = "到底了";
                        $(window).unbind('scroll');
                    }
                })
            },
            listenScroll(){
          let self = this;
                $(window).scroll(function () {
                    let scrollTop = $(window).scrollTop();
                    let windowTop = $(window).height();
                    let documentTop = $(document).height();
                    if(documentTop - windowTop <= scrollTop){
                        self.page++;
                        self.loading = true;
                        self.getServerData();
                    }
                });
            }
        }
    }
</script>

  

  精妙的地方在 getServerData()判斷什么時候后端的數據全了,判斷就是當前返回的數據長度小於約定的長度,說明到底了。

 如果后端是thinkPhp,由於有page()函數,那么代碼類似這樣:

  

//獲取page參數
$page = I('get.page',1);
//前后端約定每次顯示的條數
$num = 3;
$M
->where()
-> page($page,$num)
->select	

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM