在PC端开发的过程中我们经常会遇到,滚动页面底部来获取下一页的数据:
1、在html定义ref(从这里开始计算)

<div class="content" ref="scrollTopList">
.....内容........
</div>

2、在data里生明page=1,isempty: false(自定义用来获取数据时判断是否需要获取下一页),

// 监听页面滚动
		mounted() {
			this.$refs.scrollTopList.addEventListener("scroll", this.throttle(this.handleScroll, 500), true)
		},

3、在methods里获取滚动的位置

// 获取滚动位置
			handleScroll() {
				let scrollTop = this.$refs.scrollTopList.scrollTop, //变量scrollTop是滚动条滚动时,距离顶部的距
					clientHeight = this.$refs.scrollTopList.clientHeight, //变量windowHeight是可视区的高度
					scrollHeight = this.$refs.scrollTopList.scrollHeight, //变量scrollHeight是滚动条的总高度
					height = 79; //根据项目实际定义
				if (scrollTop + clientHeight >= scrollHeight - height && !this.isempty) {
					this.isempty = true;
					this.page = parseInt(this.page) + parseInt(1);//页数+1
					this.Mycrea(); //调用列表list接口方法
				} else {
					return false
				}
			},
// 节流函数(防止数据一直加载)
			throttle(func, wait) {
				let lastTime = null
				let timeout
				return () => {
					let context = this;
					let now = new Date();
					let arg = arguments;
					if (now - lastTime - wait > 0) {
						if (timeout) {
							clearTimeout(timeout)
							timeout = null
						}
						func.apply(context, arg)
						lastTime = now
					} else if (!timeout) {
						timeout = setTimeout(() => {
							func.apply(context, arg)
						}, wait)
					}
				}
			},
			

4、最后一步我们获取后台数据列表时做的一些判断

Mycrea() {
				// 列表
				MycreaHttp({
					page: this.page
				}).then((ref) => {
					if (ref.code == 200) {
						this.isempty = false;
						this.Datalist2 = this.Datalist2.concat(ref.data)//合并数组,当请求到下一页数据时保留上页数据。
					//判断每页小于后台规定条数,不加载下一页数据
						if (ref.data.length <= 7) {
							this.isempty = true;
						}
					}
				})
			},

5、在离开页面时,记得销毁要不然会影响项目速度。

// 销毁
		destroyed() {
			window.removeEventListener('scroll', this.throttle(this.handleScroll, 500), true)
		},

这样就可以在Pc端实现滚动底部加载下一页数据了。

更多推荐

PC端滚到底部加载下一页数据