0

In my component, I've installed a dependency called vue2-smooth-scroll that allows me to scroll to my target element based on its id. This is the code to achieve that:

<a href="#test" class="mouse-icon" @click.prevent="preventDefault" v-smooth-scroll>

I was able to scroll to the element, with an id of #test as shown in the following code

<div id="test"></div>

However, I notice that the id "test" will be appended at the end of the URL. how do you stop that from happening? For example,

http://localhost:8081/#/test

5
  • try <div><a href="javascript:void(0);" onclick="window.scroll(0,1);">click here</a></div> Commented May 11, 2019 at 5:48
  • Hi @MayuriPansuriya How do you scroll to a specific element based on its ID with your code? Commented May 11, 2019 at 6:09
  • So what's your preventDefault method? Because you're calling this method with @click? Commented May 11, 2019 at 6:39
  • The location hash is actually set by vue2-smooth-scroll. You probably have to modify the plugin itself. Commented May 11, 2019 at 7:44
  • @tony19 How do I modify it? I am not sure what the code does. Commented May 11, 2019 at 7:51

2 Answers 2

3

To prevent href default behavior from changing URL. You can listen for the click event then call preventDefault or in VueJS you can add prevent click modifier.

It would be like:

<a href='#test' @click.prevent>Anchor</a>

But this will not work for you case because vue2-smooth-scroll intentionally set hash on the URL. As you can see in the source code on line 48 and line 70.

So you can dirty set it back but it needs to be after animation finished.

<template>
  <a href='#test' @click='setUrlBack' v-smooth-scroll>Anchor</a>
</template>

<script>
  setUrlBack () {
    setTimeout(() => {
      history.replaceState(null, null, ' ')
    }, 550) // animation duration + a little delay
  }
</script>

Well, this is very bad idea.

Another option is ask the author to add support something like no-hash property.

Or just create your own plugin file then copy the code, paste and modify it.

Sign up to request clarification or add additional context in comments.

Comments

1

Everything from the # on (in the URL) is known as the hash. This is used by the browser for navigation and input parameters. The hash can be changed by the browser without submitting a new request to the server.

Most likely it is how SmoothScroll is implemented, and is required. If you scroll to 2 links, you can use forward and back to navigate, or create a bookmark to a link.

Even without the plugin, browsers and URLs use the hash when navigating to internal links.

Unless you have a really good reason to remove it, I would just live with it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.