·
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:

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 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.