Right now, in my Vue app, when I click a <router-link>
, it goes to the page, but to the same scroll level as the previous page (because the link simply replaces the component).
I was wondering if there was a vue-router
feature that makes the page go to the top, or I need to use some other JS programming to achieve this.
Thanks much for the help.
The Vue router has several guards and functions that are called before, during and after route changes. In your case, there is a dedicated function that allows you to override the default behaviour of scrolling, named scrollBehavior
. It is called with two route objects and an object containing an x and y coordinate, and maybe a selector that selects an element on the page to use as an offset.
To use it, change the code that defines your router and add the scrollBehavior
function:
// src/router.js
const router = new VueRouter({
// What you previously had here, such as routes
scrollBehavior (to, from, savedPosition) {
return { x: 0, y: 0 };
}
});
export default router;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With