在以前的前端刀耕火種時(shí)代要實(shí)現(xiàn)滾動(dòng)加載更多想要大家都是很快實(shí)現(xiàn)了,在vue會(huì)有一點(diǎn)麻煩,最近自己研究了一下,做了一個(gè)簡單的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;      // 設(shè)置一個(gè)開關(guān)來避免重負(fù)請求數(shù)據(jù)      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);          // 將得到的數(shù)據(jù)放到vue中的data          _this.articles = JSON.parse(response.data).stories;        })        .catch(function(error){          console.log(error);        });      // 注冊scroll事件并監(jiān)聽      window.addEventListener('scroll',function(){        // console.log(document.documentElement.clientHeight+'-----------'+window.innerHeight); // 可視區(qū)域高度        // console.log(document.body.scrollTop); // 滾動(dòng)高度        // console.log(document.body.offsetHeight); // 文檔高度        // 判斷是否滾動(dòng)到底部        if(document.body.scrollTop + window.innerHeight >= document.body.offsetHeight) {          // console.log(sw);          // 如果開關(guān)打開則加載數(shù)據(jù)          if(sw==true){            // 將開關(guān)關(guān)閉            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));                // 將新獲取的數(shù)據(jù)push到vue中的data,就會(huì)反應(yīng)到視圖中了                JSON.parse(response.data).stories.forEach(function(val,index){                  _this.articles.push(val);                  // console.log(val);                });                // 數(shù)據(jù)更新完畢,將開關(guān)打開                sw = true;              })              .catch(function(error){                console.log(error);              });            }        }      });    }  }</script><style lang="less">  *{    margin:0;    padding:0;  }  li{    list-style:none;  }</style>大致效果如下

當(dāng)然目前只是一個(gè)demo,還有更好的解決辦法大家自行補(bǔ)充。
以上這篇vue中實(shí)現(xiàn)滾動(dòng)加載更多的示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注