监听滚动事件实现数据懒加载
监听滚动事件实现数据懒加载
获取滚动条当前的位置
getScrollTop() {
let scrollTop = 0
//document.documentElement 返回对象为HTML元素
//document.documentElement.scrollTop 获取当前页面的滚动条纵坐标位置
//document.body 用于设置或返回文档体
if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop
} else if (document.body) {
scrollTop = document.body.scrollTop
}
return scrollTop
},
获取当前可视范围的高度
// 获取当前可视范围的高度
getClientHeight() {
let clientHeight = 0
//网页可见区域高: document.body.clientHeight;
//document.body指的是html节点中的body节点
//document.documentElement值得是根节点,即html节点。
//他们通常是不相等的,如果让他们相等可以设置 body,html{ height:100%} 当有滚动条的时候,这样的设置应该是不合理的!,会出现断层,百度首页因为是一屏不会出现滚动条,所以两个值是相等的。
//document.documentElement.clientHeight用来获取页面可视高度更加准确
if (document.body.clientHeight && document.documentElement.clientHeight) {
clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight)
} else {
clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight)
}
return clientHeight
},
获取文档完整的高度
// 获取文档完整的高度
getScrollHeight() {
//document.body.scrollHeight 网页正文全文高
//document.documentElement.scrollHeight 浏览器所有内容高度
return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
},
获取滚动条当前的位置
// 滚动事件触发下拉加载
onScroll() {
//文档完整的高度 - 当前可视范围的高度 - 滚动条当前的位置
if (this.getScrollHeight() - this.getClientHeight() - this.getScrollTop() <= 0) {
//这里写自己的请求函数
if (this.status <= 5) {
this.status++;
// 调用请求函数
this.axios.get('url'
).then(data => {
console.log(data)
});
}
}
},
监听滚动事件
mounted() {
this.$nextTick(function () { // 解决视图渲染,数据未更新
window.addEventListener('scroll', this.onScroll);
})
}
自己的代码图片
通过插件实现路由懒加载(vue-infinite-scroll)
npm install vue-infinite-scroll --save //下载依赖
//在main.js中导入,并使用,这样就是全局可用啦
import infiniteScroll from "vue-infinite-scroll"
Vue.use(infiniteScroll)
//v-infinite-scroll="loadMore"表示回调函数是loadMore
//infinite-scroll-disabled="busy"表示由变量busy决定是否执行loadMore,false则执行loadMore,true则不执行,看清楚,busy表示繁忙,繁忙的时候是不执行的。
//infinite-scroll-distance="30"这里30决定了页面滚动到离页尾多少像素的时候触发回调函数,30是像素值。
<div v-infinite-scroll="loadMore"
v-show="loading"
infinite-scroll-disabled="busy"
infinite-scroll-distance="30"
style="text-align:center;margin:30px"> LOADING..... </div>
data(){
return {
loading: true,
busy: true ,
}
},
methods:{
loadMore() {
this.busy = true
setTimeout(() => {
this.current++
//滚动时执行的函数
this.getData(true)
}, 500);
},
getData(e) {
const params = {
"current": this.current,
"name": this.search,
"size": this.size
}
getPostData(params).then(res => {
if (e) {
this.tableData = this.tableData.concat(res.data.data)
if (res.data.data.length == 0) {
this.busy = true
this.loading = false
} else {
this.busy = false
}
} else {
this.tableData = res.data.data
this.busy = false
}
})
},
}
有问题评论区交流呀!