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

https://firebasestorage.googleapis.com/v0/b/vue-mastery.appspot.com/o/flamelink%2Fmedia%2F5.1622835306037.gif?alt=media&token=cb0ccc0f-95ce-4801-ad07-78545e405e47

 

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

https://firebasestorage.googleapis.com/v0/b/vue-mastery.appspot.com/o/flamelink%2Fmedia%2F8.gif?alt=media&token=6ba35db8-214c-436e-967f-a9673c5c8c7a

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:

https://firebasestorage.googleapis.com/v0/b/vue-mastery.appspot.com/o/flamelink%2Fmedia%2F9.gif?alt=media&token=577f6e26-3f86-442b-9697-be68bd8cea0f

posted @   Zhentiw  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-11-26 [XState] raise event: trigger an action immediately when reach target state
2022-11-26 [Typescript] 118. Hard - IsRequiredKey
2022-11-26 [Typescript] 117. Hard - ClassPublicKeys
2020-11-26 [RxJS] Filtering operator: first
2020-11-26 [Tools] Interactively exploring a large JSON file with fx
2020-11-26 [Javascript] Broadcaster + Operator + Listener pattern -- 22. mapError, wrap fetch with broadcaster with cancellation
2020-11-26 [Javascript] Cancel a promise
点击右上角即可分享
微信分享提示