Javascript is required
·
1 min read

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

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:

1const router = new VueRouter({
2  routes: [...],
3  scrollBehavior (to, from, savedPosition) {
4    return { x: 0, y: 0 }
5  }
6})

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

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

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

1scrollBehavior (to, from, savedPosition) {
2  if (savedPosition) {
3    return savedPosition
4  } else {
5    return { x: 0, y: 0 }
6  }
7}

Official documentation

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

I will never share any of your personal data. You can unsubscribe at any time.