Mokkapps Logo

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

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
January 28, 2022
1 Minuten Lesezeit
|
- Ansichten

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

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

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 tip, follow me on Twitter to get notified about new tips, blog posts and more content from me.

Alternatively (or additionally), you can also subscribe to my newsletter.

Sie haben einen Fehler in diesem Artikel gefunden? Sie möchten gerne etwas klarstellen, aktualisieren oder hinzufügen?

Alle meine Artikel können auf Github editiert werden. Jeder Fix ist willkommen, egal wie klein er sein mag!

Ändern auf Github