nuxtjs开发的ssr网站,如何在后退时返回到上次滚动位置

nuxtjs开发的服务端渲染网站,默认刷新或者返回的时候,会自动滚动到顶部的位置;

要想去掉这个特性,我们可以在跟目录下添加app/router.scrollBehavior.js文件

其中注释掉了前进后退返回顶部的代码,编译后会覆盖默认行为

import { getMatchedComponents, setScrollRestoration } from "./utils";

if (process.client) {
	if ("scrollRestoration" in window.history) {
		setScrollRestoration("manual");

		// reset scrollRestoration to auto when leaving page, allowing page reload
		// and back-navigation from other pages to use the browser to restore the
		// scrolling position.
		window.addEventListener("beforeunload", () => {
			setScrollRestoration("auto");
		});

		// Setting scrollRestoration to manual again when returning to this page.
		window.addEventListener("load", () => {
			setScrollRestoration("manual");
		});
	}
}

export default function(to, from, savedPosition) {
	// If the returned position is falsy or an empty object, will retain current scroll position
	let position = false;

	const Pages = getMatchedComponents(to);

	// Scroll to the top of the page if...
	// if (
	// 	// One of the children set `scrollToTop`
	// 	Pages.some(Page => Page.options.scrollToTop) ||
	// 	// scrollToTop set in only page without children
	// 	(Pages.length < 2 &&
	// 		Pages.every(Page => Page.options.scrollToTop !== false))
	// ) {
	// 	position = { x: 0, y: 0 };
	// }

	// savedPosition is only available for popstate navigations (back button)
	if (savedPosition) {
		position = savedPosition;
	}

	const nuxt = window.$nuxt;

	if (
		// Route hash changes
		(to.path === from.path && to.hash !== from.hash) ||
		// Initial load (vuejs/vue-router#3199)
		to === from
	) {
		nuxt.$nextTick(() => nuxt.$emit("triggerScroll"));
	}

	return new Promise(resolve => {
		// wait for the out transition to complete (if necessary)
		nuxt.$once("triggerScroll", () => {
			// coords will be used if no selector is provided,
			// or if the selector didn't match any element.
			if (to.hash) {
				let hash = to.hash;
				// CSS.escape() is not supported with IE and Edge.
				if (
					typeof window.CSS !== "undefined" &&
					typeof window.CSS.escape !== "undefined"
				) {
					hash = "#" + window.CSS.escape(hash.substr(1));
				}
				try {
					if (document.querySelector(hash)) {
						// scroll to anchor by returning the selector
						position = { selector: hash };
					}
				} catch (e) {
					console.warn(
						"Failed to save scroll position. Please add CSS.escape() polyfill (https://github.com/mathiasbynens/CSS.escape)."
					);
				}
			}
			resolve(position);
		});
	});
}

这样刷新页面或者返回上页的时候,页面还是在原来的位置,而不是滚动到顶部

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值