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