From 9bd0c85934ddb4e3ad50773aacbdc6c69766fa26 Mon Sep 17 00:00:00 2001 From: ZTL-UwU Date: Mon, 27 May 2024 13:47:07 +0800 Subject: [PATCH] feat: smooth scrolling Signed-off-by: ZTL-UwU --- app/router.options.ts | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 app/router.options.ts diff --git a/app/router.options.ts b/app/router.options.ts new file mode 100644 index 00000000..9ae5f27f --- /dev/null +++ b/app/router.options.ts @@ -0,0 +1,38 @@ +import type { RouterConfig } from '@nuxt/schema'; + +// https://router.vuejs.org/api/interfaces/routeroptions.html +export default { + scrollBehavior(to, _form, savedPosition) { + return new Promise((resolve) => { + setTimeout(() => { + if (history.state.smooth) { + resolve({ + el: history.state.smooth, + behavior: 'smooth', + }); + } + + if (to.hash) { + const el = document.querySelector(to.hash) as any; + if (!el) + resolve({ el: to.hash, top: 0 }); + + const { marginTop } = getComputedStyle(el); + const marginTopValue = Number.parseInt(marginTop); + const offset = (document.querySelector(to.hash) as any).offsetTop - marginTopValue; + + resolve({ + top: offset, + behavior: 'smooth', + }); + } + + // Scroll to top of window + if (savedPosition) + resolve(savedPosition); + else + resolve({ top: 0 }); + }, 1); // Hack page wise navigation + }); + }, +};