Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt.js: How to override scrollBehaviour for a single route change

I have a nuxt-page where I scroll to the top on every router change. We defined this in the nuxt.config.js

scrollBehavior (to, from, savedPosition) {
  return ({ x: 0, y: 0 })
}

Now I have one single Navigation link which is a little special: «Contact» does not lead to a new page with just the contact information, but instead it should go to the footer where the contact details are written on every page. So I added a link (not a nuxtlink) to link to the #contact anchor in the footer.

  <a class="Submenu__link Submenu__link--contact" href="#contact">
    Contact
  </a>

This does not work though because it registers a route change and sets the page to the top again. (At least that is my assumption). I tried to execute some function to set the scrollTop property but then I see a flicker, where it scrolls a bit but is then reset to the top:

  <li class="Submenu__item">
    <a @click="closeNavAndScroll" class="Submenu__link Submenu__link--contact" href="#contact">
      Contact
    </a>
  </li>

And I declared a method (closing nav works):

closeNavAndScroll () {
  this.closeNavMenu()
  window.scrollTop(400)
}

So I thought I find some information here: https://nuxtjs.org/api/configuration-router#scrollBehavior

But as far as I could understand there is only a declaration for setting the scrollBehaviour for all routes. Can I somehow say whenever the route includes #contact I don't want the app to mess with my scroll position?

Thanks for any help on this.

Cheers

like image 205
Merc Avatar asked Apr 18 '18 04:04

Merc


1 Answers

Create your #contact anchor as you did, but change the scroll behavior to handle it:

scrollBehavior (to, from, savedPosition) {
  if (to.hash) {
    return {selector: to.hash}
  } else {
    return {x: 0, y: 0}
  }
}
like image 147
acdcjunior Avatar answered Oct 18 '22 06:10

acdcjunior