1. 程式人生 > >vue中實現滾動載入更多

vue中實現滾動載入更多

在以前的前端刀耕火種時代要實現滾動載入更多想要大家都是很快實現了,在vue會有一點麻煩,最近自己研究了一下,做了一個簡單的demo,供大家參考:

<template>
    <div>
        <ul>
            <li v-for="item in articles">
                <h2>{{item.title}}</h2>
                <img :src="item.images" alt="">
            </li>
        </ul>
    </div>
</template>
<script>
    import axios from 'axios';
    export default{
        data(){
            return {
                articles : []
            }
        },
        mounted(){
            // 快取指標
            let _this = this;
            // 設定一個開關來避免重負請求資料
            let sw = true;
            // 此處使用node做了代理
            axios.get('http://localhost:3000/proxy?url=http://news-at.zhihu.com/api/4/news/latest')
                .then(function(response){
                    // console.log(JSON.parse(response.data).stories);
                    // 將得到的資料放到vue中的data
                    _this.articles = JSON.parse(response.data).stories;
                })
                .catch(function(error){
                    console.log(error);
                });

            // 註冊scroll事件並監聽
            window.addEventListener('scroll',function(){
                // console.log(document.documentElement.clientHeight+'-----------'+window.innerHeight); // 可視區域高度
                // console.log(document.body.scrollTop); // 滾動高度
                // console.log(document.body.offsetHeight); // 文件高度
                // 判斷是否滾動到底部
                if(document.body.scrollTop + window.innerHeight >= document.body.offsetHeight) {
                    // console.log(sw);
                    // 如果開關開啟則載入資料
                    if(sw==true){
                        // 將開關關閉
                        sw = false;
                        axios.get('http://localhost:3000/proxy?url=http://news.at.zhihu.com/api/4/news/before/20170608')
                            .then(function(response){
                                console.log(JSON.parse(response.data));
                                // 將新獲取的資料push到vue中的data,就會反應到檢視中了
                                JSON.parse(response.data).stories.forEach(function(val,index){
                                    _this.articles.push(val);
                                    // console.log(val);
                                });
                                // 資料更新完畢,將開關開啟
                                sw = true;
                            })
                            .catch(function(error){
                                console.log(error);
                            });   
                    }
                }
            });
        }
    }
</script>
<style lang="less">
    *{
        margin:0;
        padding:0;
    }
    li{
        list-style:none;
    }
</style>
大致效果如下:

當然目前只是一個demo,還有更好的解決辦法大家自行補充。