From 0ed71b8e62783173dad9699b3fda5fda60a127a6 Mon Sep 17 00:00:00 2001 From: Elirehema Date: Sun, 28 Feb 2021 01:00:35 +0300 Subject: [PATCH] Ovveride scroll behaviour --- nuxt.config.js | 32 -------------------------------- router.scrollBehavior.js | 30 +++++++++++++++++++++++------- 2 files changed, 23 insertions(+), 39 deletions(-) diff --git a/nuxt.config.js b/nuxt.config.js index 1248d6f9..e520b75b 100644 --- a/nuxt.config.js +++ b/nuxt.config.js @@ -5,40 +5,8 @@ export default { router: { base: process.env.NODE_ENV === "production" ? "/docs/" : "/", routerNameSplitter: "/", - scrollBehavior: async function(to, from, savedPosition) { - if (savedPosition) { - return savedPosition; - } - - const findEl = async (hash, x = 0) => { - return ( - document.querySelector(hash) || - new Promise(resolve => { - if (x > 50) { - return resolve(document.querySelector("#app")); - } - setTimeout(() => { - resolve(findEl(hash, ++x || 1)); - }, 100); - }) - ); - }; - - if (to.hash) { - let el = await findEl(to.hash); - if ("scrollBehavior" in document.documentElement.style) { - return window.scrollTo({ top: el.offsetTop, behavior: "smooth" }); - } else { - return window.scrollTo(0, el.offsetTop); - } - } - - return { x: 0, y: 0 }; - } - }, - loadingIndicator: { name: 'pulse', color: ' #00A756', diff --git a/router.scrollBehavior.js b/router.scrollBehavior.js index 65cb2f13..4a4ccdea 100644 --- a/router.scrollBehavior.js +++ b/router.scrollBehavior.js @@ -1,8 +1,24 @@ -export default function (to, from, savedPosition) { - if (to.hash) { - return { - selector: to.hash - // , offset: { x: 0, y: 10 } - } +export default function(to, from, savedPosition) { + const defaultPosition = false; + const scrollTopPosition = { x: 0, y: 0 }; + + let position = defaultPosition; + console.log({ to, from }); + if (savedPosition) { + position = savedPosition; + } else if (to.matched.length < 2) { + position = scrollTopPosition; + } else if (to.matched.some(child => child.components.default.options.scrollToTop)) { + position = scrollTopPosition; + } + + return new Promise(resolve => { + window.$nuxt.$once('triggerScroll', () => { + if (to.hash && document.querySelector(to.hash)) { + position = { selector: to.hash }; } - } \ No newline at end of file + + resolve(position); + }); + }); +} \ No newline at end of file