为了解决 分页切换时页面滚动到顶部 的问题(尤其是 Vue + Element Plus 表格组件中常见)
Step 1:分页前,锁住滚动位置
const lockScroll = () => {
const scrollY = window.scrollY || document.documentElement.scrollTop;
document.body.style.position = "fixed";
document.body.style.top = `-${scrollY}px`;
document.body.style.width = "100%";
return scrollY;
};
Step 2:分页后,解锁滚动并还原位置
const unlockScroll = (scrollY: number) => {
document.body.style.position = "";
document.body.style.top = "";
document.body.style.width = "";
window.scrollTo(0, scrollY);
};
Step 3:修改你的分页调用逻辑(完整代码)
const getTabData = async () => {
const scrollY = lockScroll(); // 锁住滚动
const listObj = {
...returnQueryParams(),
pageNumber: queryParams.pageNum,
pageSize: queryParams.pageSize,
};
try {
const {
data: { data = [], total = 0 },
} = await aGetlist(listObj);
atotal.value = total;
listData.value = data;
} catch (error) {
atotal.value = 0;
listData.value = [];
} finally {
nextTick(() => {
unlockScroll(scrollY); // 解锁滚动
});
}
};