在_app.js里面加入下面代码
import Router from "next/router"
initRouterListeners()
function initRouterListeners() {
const routes = [];
Router.events.on("routeChangeStart", url => {
pushCurrentRouteInfo();
});
Router.events.on("routeChangeComplete", url => {
window.requestAnimationFrame(() => window.scrollTo(0, 1));
fixScrollPosition();
});
function pushCurrentRouteInfo() {
routes.push({ pathname: Router.pathname, scrollY: window.scrollY });
}
function isBack() {
return routes.length >= 2 && Router.pathname === routes[routes.length - 2].pathname;
}
function fixScrollPosition() {
let scrollY = 0;
if (isBack()) {
routes.pop();
const targetRoute = routes.pop();
scrollY = targetRoute.scrollY;
}
window.requestAnimationFrame(() => window.scrollTo(0, scrollY));
}
}
注意:对于返回页面的数据是分页获取的,不适用此方法