Vue Tip: Scroll to Top When Navigating to a New Route
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:
The following code scrolls to the top of the page for all route navigations:
To achieve a native-like behavior when navigating with back/forward buttons we can return savedPosition
:
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:
Vue Tip: Display Raw HTML
The double mustaches interpret the data as plain text, not HTML. To output real HTML, you will need to use the v-html directive.
Vue Tip: Speed Up Initial Load Using Async Components
Using async components is a great way to speed up the initial load time of your app.