[Vue Router] Scroll Behavior
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:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步