Skip to content

Instantly share code, notes, and snippets.

@rylanharper
Created November 25, 2024 02:28
Show Gist options
  • Select an option

  • Save rylanharper/efb44d489d146c9f0a13b0b899747668 to your computer and use it in GitHub Desktop.

Select an option

Save rylanharper/efb44d489d146c9f0a13b0b899747668 to your computer and use it in GitHub Desktop.
Nuxt3 `router.options.ts` update; scroll jump fix
import type { RouteLocationNormalized } from '#vue-router';
import type { RouterConfig } from 'nuxt/schema';
import { START_LOCATION } from 'vue-router';
import { useNuxtApp } from '#app/nuxt';
function calculatePosition(
to: RouteLocationNormalized,
savedPosition: ScrollToOptions | null,
behavior: ScrollBehavior = 'auto'
): ScrollToOptions {
// Return saved position if available
if (savedPosition) return savedPosition;
// Scroll to element if hash is provided
if (to.hash) {
const element = document.querySelector(to.hash);
const top = element ? element.getBoundingClientRect().top + window.scrollY : 0;
return { top, left: 0, behavior };
}
// Default scroll to top of the page
return { top: 0, left: 0, behavior };
}
export default <RouterConfig>{
scrollBehavior: (to, from, savedPosition) => {
const isFirstLoad = from === START_LOCATION;
const nuxtApp = useNuxtApp();
// Restore saved position on first load
if (isFirstLoad && savedPosition) {
window.history.scrollRestoration = 'auto';
return savedPosition;
}
// Set manual scroll restoration for subsequent navigations
window.history.scrollRestoration = 'manual';
return new Promise((resolve) => {
nuxtApp.hooks.hookOnce('page:finish', () => {
nextTick(() => {
requestAnimationFrame(() => {
resolve(calculatePosition(to, savedPosition, 'instant'));
});
});
});
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment