我是靠谱客的博主 自由小天鹅,这篇文章主要介绍【vue】实现滚动条滚动到底部时发送请求获取数据,现在分享给大家,希望可以做个参考。

当后端给我们一个分页获取数据的接口时,我们前端可以通过设置分页按钮来获取到所有的数据,也可以通过判断滚动条位置,当滚动条滚动到底部时就发送请求获取下一页的数据,这样我们就可以不设置分页按钮也能获取到所有的数据。

要实现这个功能最主要的就是判断滚动条的位置:

如下图所示:

clientHeight表示可视区域的高;

scrollTop表示滚动条距离可视区域顶部的距离;

scrollHeight表示滚动内容的高度;

由上图我们可以得出滚动条到达底部的条件:

复制代码
1
scrollHeight = scrollTop + clientHeight

代码实现:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<template> <div> <div ref="scrollBox" class="box" @scroll="toLoadMore"> <div v-for="item in boxData" :key="item.id">{{item.name}}</div> <div v-loading='loading'></div> </div> </div> </template> <script> import { getEnumValuePage } from "@/api/index" export default { data(){ return { boxData: [], // 当前页码 currentPage: 1, // 添加loading动画 loading: true,       // 是否最后一页,如果最后一页了就不再发送请求了 lastPage: false } }, methods:{ getBoxData(){ this.loading = true       //传给后端的参数 let params = {     currentPage: this.currentPage     } //发送请求 if(!this.lastPage){ getEnumValuePage(params).then(res=>{ if(res.status === 0){ this.boxData.push(...(res.data.list)) this.loading = false if(res.data.list.length < 36){ //一页总共36条数据,小于36条时,表示是最后一页了 this.lastPage = true } } }) } }, toLoadMore(){ let scrollDom = this.$refs.scrollBox // console.log(scrollDom.clientHeight,'clientHeight'); //scrollDom 可视区域的高 290px // console.log(scrollDom.scrollHeight,'scrollHeight'); //scrollDom 里面的内容的高 // console.log(scrollDom.scrollTop,'scrollTop'); //滚动条距离scrollDom顶部的距离 // 由于scrollTop不太准确,所以这里加了个1 if(scrollDom.clientHeight + scrollDom.scrollTop + 1 >= scrollDom.scrollHeight){ this.currentPage ++ //页数加一 this.getBoxData() //发送请求获取数据 } }, }, mounted(){ this.getBoxData() } } </script> <style scoped lang='scss'> .box{ width: 200px; height: 300px; border: 5px solid black; overflow-y: auto; &>div{ padding-left: 15px; line-height: 30px; background: rgba(255, 192, 203, 0.7); } } </style>

效果展示:

最后

以上就是自由小天鹅最近收集整理的关于【vue】实现滚动条滚动到底部时发送请求获取数据的全部内容,更多相关【vue】实现滚动条滚动到底部时发送请求获取数据内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(61)

评论列表共有 0 条评论

立即
投稿
返回
顶部