In my Vue/Vuetify single page app, when I scroll down a page and click the link at the bottom of the page, it does change the route and takes me to the next page but it doesn't scroll to the top of the next page/Component.
As a result, if the first page is lengthy and 2nd page has few contents, it gives an impression that the 2nd page lacks the contents. Since the contents are visible only if user scroll to the top of the page.
Page 01 - I'm in the middle of a long list, just a example
Page 02 - The next Component loads at the middle
You can use the above code to scroll top. const didMount = useDidMount(); const router = useRouter(); const { asPath } = router; useEffect(() => { if (didMount) { scrollToPosition(); } }, [asPath]); And add the above code to the top parent component. Save this answer.
How to return to the same scroll position when going back using useNavigate() or useLocation() react-router.
You can use vue-router's scrollBehavior
method to change the scroll position on page navigation. Instead of created () { window.scrollTo(0, 0) }
you should use:
new VueRouter ({
routes: [...],
scrollBehavior () {
return { x: 0, y: 0 }
}
})
See more examples on vue-router's documentation:
https://router.vuejs.org/guide/advanced/scroll-behavior.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With