Router-link-active on vue-router activates all the hash links on homepage route

Viewed 371

I have this navigation that scrolls to a section on homepage, except for the contact route.

Because my contact page is not on the same route I had to use scroll behaviour so i can go from contact to some section on homepage (links didn't work otherwise).

So now that I made that work I have another problem. Router-link-active class activates all the routes with hash property that are on the homepage.

How can I bypass this, I have tried to remove this classes and make custom active class on-click, but it's still not working.

<li><router-link to="/">Home</router-link></li>
<li><router-link :to="{name: 'home', hash: '#about'}">About</router-link></li>
<li><router-link :to="{name: 'home', hash: '#courses'}">Courses</router-link></li>
<li><router-link :to="{name: 'home', hash: '#news'}">News</router-link></li>
<li><router-link :to="{name: 'home', hash: '#business-incubator'}">Business incubator</router-link></li>
<li><router-link :to="{name: 'home', hash: '#team'}">Team</router-link></li>
<li><router-link  to="/contact">Contact</router-link></li>

I understand it activates all the links because they are all on the same name: 'home', but that is the only way I made scroll-to work. So, if there is a better and proper way to do this, please help. Thanks.

Edit: this is the scroll behaviour code:

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior: function (to) {
    return new Promise((resolve) => {
      setTimeout(() => {
        if (to.hash) {
          resolve({ el: to.hash, top: 140, behavior: 'smooth',  })
        } else {
          resolve({ top: 0, behavior: 'smooth' })
        }
        
      }, 300)
    })
  }
});
0 Answers
Related