[Vue Router] Scroll Behavior

Zhentiw發表於2024-11-26

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

相關文章