監聽元素內部滾動條事件,滾動到底部加載數據,也可以使用插件進行滾動加載處理
方法一、監聽滾動條事件滾動加載
1、dom結構:最外層dom
<div class="scrollWrap"> </div>
2、mounted:初始化監聽
//mounted監聽處理
this.$nextTick (() => {
if (document.querySelector ('.scrollWrap')) {
const selectWrap = document.querySelector ('.scrollWrap');
selectWrap.addEventListener ('scroll', this.scrollLoadMore);
}
});
3、this.scrollLoadMore:方法 ------- 主要
/**
* 監聽滾動條
* scrollTop爲滾動條在Y軸上的滾動距離。
* clientHeight爲內容滾動區域的高度。
* scrollHeight爲內容可視區域的高度加上溢出(滾動)的距離。
* */
scrollLoadMore () {
let scrollWrap = document.querySelector ('.scrollWrap');
var currentScrollTop = scrollWrap.scrollTop;
var currentOffsetHeight = scrollWrap.scrollHeight;
var currentClientHeight = scrollWrap.clientHeight;
if ((currentScrollTop + currentClientHeight === currentOffsetHeight) && (this.pageConfig.pageNum <= this.pageConfig.pages)) {
//到底部了 重新請求數據
this.pageConfig.pageNum++; //頁碼++
//TODO 執行加載數據方法
}
}
4、滾動加載數據方面處理
//oriResult:[]; 存儲源數據
//dataList:[]; 存儲渲染列表數據
//result後臺返回數據
this.dataList = this.oriResult.concat (result);
this.oriResult = this.dataList;
方法二:使用vue插件:vue-pull-to
1、安裝:
npm install vue-pull-to --save
2、引用註冊
引用:
import PullTo from 'vue-pull-to';
註冊:
components: {
PullTo
}
3、使用:
官網地址:https://github.com/stackjie/vue-pull-to/blob/master/README.zh-CN.md
<pull-to
:bottom-config="BOTTOM_DEFAULT_CONFIG"
:top-config="TOP_DEFAULT_CONFIG"
:is-top-bounce="false"
:is-bottom-bounce="false"
@infinite-scroll="scrollLoadMore" //請求數據方法
>
<li class="TaskLine" v-for="(item,index) of list" :key="item.index">
<div></div>
<div></div>
<div></div>
</li>
</pull-to>
scrollLoadWeikeMore () {
this.pageConfig.pageNum++;
// 加載數據
}
//下拉配置
const TOP_DEFAULT_CONFIG = {
pullText: '下拉刷新', // 下拉時顯示的文字
triggerText: '釋放更新', // 下拉到觸發距離時顯示的文字
loadingText: '', // 加載中的文字
doneText: '加載完成', // 加載完成的文字
failText: '加載失敗', // 加載失敗的文字
loadedStayTime: 400, // 加載完後停留的時間ms
stayDistance: 50, // 觸發刷新後停留的距離
triggerDistance: 70,// 下拉刷新觸發的距離
};
//上拉配置
const BOTTOM_DEFAULT_CONFIG = {
pullText: '上拉加載',
triggerText: '釋放更新',
loadingText: '加載中...',
doneText: '加載完成',
failText: '加載失敗',
loadedStayTime: 400,
stayDistance: 50,
triggerDistance: 70
};
交流
可添加qq羣共同進階學習: 進軍全棧工程師疑難解 羣號: 856402057
對前端技術保持學習愛好者。我會經常分享自己所學所看的乾貨,在進階的路上,共勉!歡迎關注公衆號共同學習。