Javascript is required
Mokkapps LogoMichael Hoffmann

Vue Tip: Scroll to Top When Navigating to a New Route

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Jan 28, 2022
1 min read
|
117 views
Router
Vue Tip: Scroll to Top When Navigating to a New Route Image

When using client-side routing using Vue Router we may want to scroll to the top when navigating to a new route or preserve the scrolling position of history entries.

Vue Router allows us to customize the scroll behavior on route navigation completely.

Warning

This feature only works if the browser supports history.pushState.

When creating the router instance, we can provide the scrollBehavior function:

const router = new VueRouter({  routes: [...],  scrollBehavior (to, from, savedPosition) {    return { x: 0, y: 0 }  }})

The following code scrolls to the top of the page for all route navigations:

scrollBehavior (to, from, savedPosition) {  return { x: 0, y: 0 }}

To achieve a native-like behavior when navigating with back/forward buttons we can return savedPosition:

scrollBehavior (to, from, savedPosition) {  if (savedPosition) {    return savedPosition  } else {    return { x: 0, y: 0 }  }}

Official documentation


If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter.