滚动到底部分页实现的原理:
1.监听滚动事件,滚动到底部100px的时候去请求接口获取分页数据
2.将接口返回的数据和页面原有的数据相加
3.如果当前页等于总页数,显示‘没有更多了’
4.如果一开始就没有数据,显示‘暂无记录’
5.滚动的事件要考虑事件节流,不然在滚动的时候一直去计算着滚动高度,耗资源
html
{{item.car_owner_earns}}
没有更多了
暂无记录
vue js
export default {
name: 'Wallet',
data() {
// EVENT_DATA_FLOW: 定义获取数据事件
// CURRENT_PAGE_INDEX: 当前页
// LOCK_STATUS: 当在请求数据时,滚动时锁定不能再发送分页请求
// loading: 加载提示框
// bill_list: 账单列表
return {
EVENT_DATA_FLOW : "ajax_data_pulled",
CURRENT_PAGE_INDEX : 1,
LOCK_STATUS : false,
loading: true,
bill_list: [],
}
},
methods: {
//获取数据函数
scrollHandler : function (e){
//如果已经在加载数据,不可以重复加载
if (this.LOCK_STATUS) return;
if (e instanceof Event) {
var el = e.target;
var scHeight = el.scrollHeight, scTop = el.scrollTop, clHeight = el.clientHeight;
//距离底部100px时,开始加载数据
if (scHeight - scTop > clHeight + 100) return;
}
this.LOCK_STATUS = true;
this.$xhr.post('你的url', {
page: this.CURRENT_PAGE_INDEX,
length: 15
}, {loading:'加载中...'}).then( (res) => {
//调用拼接数据事件
this.$event.emit(this.EVENT_DATA_FLOW,{
bill_list : res.data.list,
total_page : res.data.total_page
});
++this.CURRENT_PAGE_INDEX;
this.LOCK_STATUS = false;
}).catch (() => {
this.LOCK_STATUS = false;
});
},
//滚动时对滚动事件进行节流
scrollEvent: function (e) {
this.throttled(this.scrollHandler(e), 300)
},
//节流
throttled: function (func, wait, options) {
var self = this;
var timeout, context, args, result
var previous = 0
if (!options) options = {}
var later = function () {
previous = options.leading === false ? 0 : self.now()
timeout = null
result = func.apply(context, args)
if (!timeout) context = args = null
}
var throttled = function () {
var now = self.now()
if (!previous && options.leading === false) previous = now
var remaining = wait - (now - previous)
context = this
args = arguments
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout)
timeout = null
}
previous = now
result = func.apply(context, args)
if (!timeout) context = args = null
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining)
}
return result;
}
throttled.cancel = function () {
clearTimeout(timeout)
previous = 0
timeout = context = args = null
}
return throttled;
},
now: function () {
return new Date().getTime();
},
//初始化监听事件
initPage : function () {
this.$event.on(this.EVENT_DATA_FLOW, (e) => {
if(this.CURRENT_PAGE_INDEX === e.total_page){
//如果等于最后一页,就停止滚动
this.loading = false;
}
if (e.bill_list instanceof Array) {
//将现有页面的数据和接口返回的数据相加
this.bill_list = this.bill_list.concat(e.bill_list);
return;
}
});
},
},
mounted() {
this.initPage();
//call scrollHandler when page inited
this.scrollHandler();
}
}