·

Vue - Go to anchor smoothly without changing url

Published at 2024-04-30 16:52:12Viewed 283 times
Professional article
Please reprint with source link

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.

Comments

There is no comment, let's add the first one.

弦圈热门内容

Vertically aligning CSS :before and :after content

I am trying to centre the link with the image, but can't seem to move the content vertically in any way.&lt;h4&gt;More Information&lt;/h4&gt; &lt;a href="#" class="pdf"&gt;File Name&lt;/a&gt;The icon is 22 x 22px.pdf { font-size: 12px; } .pdf:before { padding:0 5px 0 0; content: url(../img/icon/pdf_small.png); } .pdf:after { content: " ( .pdf )"; font-size: 10px; } .pdf:hover:after { color: #000; }

Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved