Menu Close

How to scroll to top of new page route with Vue.js?

Sometimes, we want to scroll to top of new page route with Vue.js.

In this article, we’ll look at how to scroll to top of new page route with Vue.js.

How to scroll to top of new page route with Vue.js?

To scroll to top of new page route with Vue.js, we can add the scrollBehavior method when we’re creating the Vue Router instance.

For instance, we write

export default new Router({
  scrollBehavior() {
    return { x: 0, y: 0 };
  },
  routes: [
    {
      path: "/",
      name: "Home",
      component: Home,
    },
  ],
  mode: "history",
});

to add the scrollBehavior method that returns an object with the x and y coordinates to scroll to when we change routes.

Conclusion

To scroll to top of new page route with Vue.js, we can add the scrollBehavior method when we’re creating the Vue Router instance.

Posted in vue