Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When route change to next Component, don't scroll to the top automatically

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

enter image description here

Page 02 - The next Component loads at the middle

enter image description here

like image 600
extraxt Avatar asked Nov 15 '17 14:11

extraxt


People also ask

How do you scroll to top on route change with react Dom v6?

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 do you return to the exact same scroll position when going back to previous page react?

How to return to the same scroll position when going back using useNavigate() or useLocation() react-router.


1 Answers

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

like image 94
Kael Watts-Deuchar Avatar answered Oct 13 '22 22:10

Kael Watts-Deuchar