scroll to top router link vue

<template>
  <div>
    <router-link
      to="/"
      @click.native="scrollToTop"
    >
      Home
    </router-link>
    <router-view />
  </div>
</template>

<script>
export default {
  methods: {
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    }
  }
};
</script>

Explanation:

  1. Template Section:
  2. <div>: This contains the content of the Vue component.
  3. <router-link>: This is a navigation link provided by Vue Router. It navigates to the root URL ("/") which represents the Home page.
  4. @click.native="scrollToTop": This is a click event handler that triggers the scrollToTop method when the router link is clicked.

  5. Script Section:

  6. scrollToTop() method: This method is defined to scroll the window to the top.
    • window.scrollTo(): It scrolls the window to the specified coordinates.
    • top: 0: Scrolls to the top of the page (Y-axis = 0).
    • behavior: 'smooth': Specifies the scrolling behavior to be smooth for a more visually pleasing effect.

This code sets up a Vue component with a router link that, when clicked, triggers a method (scrollToTop()) to smoothly scroll the window to the top of the page.