Vue - Go to anchor smoothly without changing url
In Vue.js, we can define an anchor by RouterLink
or HTML tag <a>
, while in Nuxt.js, we can additionally use NuxtLink
which is similar to RouterLink
.
<a href="#content">My Link</a>
<RouterLink to="#content">My Link</RouterLink>
<NuxtLink to="#content">My Link</NuxtLink>
However, on loading a page, the above ways would change the url which makes it slow to go to #content
. To speed up anchor link and not change the url, there are two ways.
The first way is to use pure javascript method scrollIntoView
to scroll to the specified div id, which is fast and would not change url.
function scrollSmoothTo(Id) {
var node = document.getElementById(Id);
node.scrollIntoView({
behavior: 'smooth'
});
}
<a @click="scrollSmoothTo('content')">
Scroll to userdiv
</a>
<RouterLink @click="scrollSmoothTo('content')">
Scroll to userdiv
</RouterLink>
<NuxtLink @click="scrollSmoothTo('content')">
Scroll to userdiv
</NuxtLink>
<div id="content">
example
</div>
Note that adding behavior: 'smooth'
can add animation when scrolling. However, using this way, a
could not have attribute href, i.e.
<a href="#content" @click="scrollSmoothTo('content')" />
<RouterLink href="#content" @click="scrollSmoothTo('content')" />
<NuxtLink href="#content" @click="scrollSmoothTo('content')" />
would not perform the click event. This is not SEO friendly.
Therefore, the second way is the improvement of the first that is SEO friendly, which can smoothly go to #content
without changing the url. We should use Vue's event modifiers for v-on
.
<a href="#content" @click.native.prevent="scrollSmoothTo('content')">
Scroll to userdiv
</a>
<div id="content">
example
</div>
This way, we could prevent the default href action when clicking and perform the scrollSmoothTo function. However, It seems that using RouterLink
or NuxtLink
in the same way could not prevent the default action, i.e.
<RouterLink href="#content" @click.native.prevent="scrollSmoothTo('content')">
Scroll to userdiv
</RouterLink>
<NuxtLink href="#content" @click.native.prevent="scrollSmoothTo('content')">
Scroll to userdiv
</NuxtLink>
not work.
There is no comment, let's add the first one.