Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue Router go to top on new page

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.

like image 462
J.Ko Avatar asked Dec 08 '18 22:12

J.Ko


1 Answers

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;
like image 158
Sumurai8 Avatar answered Oct 10 '22 10:10

Sumurai8