Categories
Vue Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *