滚动条下拉触底后加载数据
触底加载
- 需求:页面下拉滚动条,容器元素触底后发起接口请求获取第二批数据(类似于懒加载)
- 浏览器API:getBoundingClientRect,判断元素底部边界是否出现在页面视窗。
- 注意:防抖和节流,控制触发次数
js:
import { debounce } from 'lodash';
const searchForm = reactive({
page: 1,
pageSize: 20,
});
const tableConfig = reactive({
total: 0,
tableData: [],
hasMore: false,
});
async function getTableData() {
try {
const res = await getSmokeCarList(searchForm);
const { list } = res.data;
if (list.length < searchForm.pageSize) {
tableConfig.hasMore = false;
} else {
tableConfig.hasMore = true;
}
tableConfig.tableData = tableConfig.tableData.concat(list);
} catch (error) {
console.log(error);
}
}
// div底部出现在视窗时加载数据
const carListRef = ref();
// 使用防抖,限制触发频率
const debouncedLoadMore = debounce(() => {
const rect = carListRef.value.getBoundingClientRect();
// 判断元素的下边界是否在视窗内
const isInViewport = rect.bottom > 0 && rect.bottom <= window.innerHeight;
if (isInViewport && tableConfig.hasMore) {
searchForm.page += 1;
getTableData();
}
}, 500); // 指定防抖延迟时间
onMounted(() => {
window.addEventListener('scroll', debouncedLoadMore);
getTableData();
});
onUnmounted(() => {
window.removeEventListener('scroll', debouncedLoadMore);
});
html:
<div ref="carListRef" class="table-box">
容器内容
</div>