vue无限滚动加载
1、使用防抖完成无限加载
export default {
data() {
return {
menuList: {},
time: null,
page: 1,
loading: true,
};
},
methods: {
windowScroll() {
this.time = null;
window.addEventListener("scroll", () => {
if (this.time) {
clearTimeout(this.time);
}
this.time = setTimeout(() => {
const window_height = document.body.scrollHeight; //滚动条总高度
const scrollTop = document.documentElement.scrollTop; //滚动条距离顶部距离
const clientHeight = document.documentElement.clientHeight; //页面可视区高度
if (scrollTop + clientHeight >= window_height - 20) {
menuPush();
}
}, 300);
});
const menuPush = async () => {
if (this.page < this.menuList.total / this.menuList.page_size) {
this.loading = true;
this.page = this.page + 1;
const list = (await getMenuQuery({ page: this.page })).data.list;
this.menuList.list = this.menuList.list.concat(list);
this.loading = false;
}
};
},
},
async mounted() {
this.windowScroll();
this.menuList = (await getMenuQuery({ page: this.page })).data;
this.loading = false;
},
};
2、使用throttle-debounce
- 下载 throttle-debounce npm i throttle-debounce
- 引用 import { throttle } from "throttle-debounce";
//引入节流
import { throttle } from "throttle-debounce";
export default {
data() {
return {
menuList: [],
isloading: false,
page: 1,
};
},
//挂载完成
async mounted() {
//获取菜单数据
const menuList = await getMenu({ page: this.page });
this.menuList = menuList.data.list;
//throttle() 返回值是一个节流函数
this.throttle = throttle(1000, this.scroll.bind(this));
// 绑定滚动事件
window.addEventListener("scroll", this.throttle);
},
methods: {
//滚动
scroll() {
//正在加载时,不再重复调用数据
if (this.isloading) {
return;
}
//getBoundingClientRect()
// 获取浏览器内部窗口的高度
const h = window.document.documentElement.clientHeight;
// 获取列表底部距视口顶部的距离
const l = this.$refs.list.$el.getBoundingClientRect().bottom;
if (h > l) {
// 触底
this.isloading = true;
//获取下一页
this.page++;
// 加载数据,获取第二页的内容
//防抖和节流
getMenu({ page: this.page }).then((res) => {
//隐藏提示
this.isloading = false;
//将数据放到 menuList 中
//...展开运算符
this.menuList.push(...res.data.list);
});
}
},
},
};
https://blog.csdn.net/u011818572/article/details/79117861
标签:vue,throttle,const,list,page,滚动,data,menuList,加载 From: https://www.cnblogs.com/Lmyong/p/16924247.html