Notice how when we are on Google and search for Vue Mastery, when we scroll down and click on the next button, we show up at the top of the second page of results:
Luckily we can easily give our application this functionality, by adding a little code to our router:
📃 /src/router/index.js
...
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
scrollBehavior() { // <---
// always scroll to top
return { top: 0 }
}
})
...
but there’s another behavior that we might want. On Google, when we scroll to the bottom of a page, click to go to the next page, and then use the back button, we’re brought back to where we just were (scrolled to the bottom of the page).
This is a behavior we don’t really think about, but we come to expect. When we hit the back button, we expect to be brought back to where we just left. However, we just told our Vue application to go to the top of the page on every navigation (even back).
To go back to the same part of the page we just left, it’s a small modification:
..
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
scrollBehavior(to, from, savedPosition) {
if (savedPosition) { // <----
return savedPosition
} else {
return { top: 0 }
}
}
})
...
If there is a saved position for this page, now it will properly go back to where we just were. We can see this inside our event example: