From 66668701f8ccc5b5b125d2478b3fc616c2cdc901 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bahad=C4=B1r=20Sofuo=C4=9Flu?= Date: Wed, 28 Dec 2022 01:53:08 +0300 Subject: [PATCH] Scrolltotop issue fixed for history back routes --- middleware/route.global.js | 9 --------- plugins/scrollToTop.js | 23 +++++++++++++++++++++++ 2 files changed, 23 insertions(+), 9 deletions(-) delete mode 100644 middleware/route.global.js create mode 100644 plugins/scrollToTop.js diff --git a/middleware/route.global.js b/middleware/route.global.js deleted file mode 100644 index a763923e1..000000000 --- a/middleware/route.global.js +++ /dev/null @@ -1,9 +0,0 @@ -export default defineNuxtRouteMiddleware((to, from) => { - useNuxtApp().hook('page:finish', () => { - if (to.path !== from.path && history.state.scroll) { - window.scrollTo(history.state.scroll); - } else { - window.scrollTo(0, 0); - } - }); -}); diff --git a/plugins/scrollToTop.js b/plugins/scrollToTop.js new file mode 100644 index 000000000..e4977e4a3 --- /dev/null +++ b/plugins/scrollToTop.js @@ -0,0 +1,23 @@ +export default defineNuxtPlugin((nuxtApp) => { + nuxtApp.$router.options.scrollBehavior = async (to, from, savedPosition) => { + let goTo; + + if (to.hash) { + console.log(to); + goTo = { + el: to.hash, + top: 0 + }; + } else if (savedPosition) { + goTo = savedPosition; + } else { + goTo = { top: 0 }; + } + + return new Promise((resolve) => { + setTimeout(() => { + resolve(goTo); + }, 100); + }); + }; +});