Home > other >  Navigating with nuxt-link to anchor/hash on a different page is not working
Navigating with nuxt-link to anchor/hash on a different page is not working

Time:11-04

I want to navigate to a specific section of a page from another page. So I added the scrollBehavior function in router object in nuxt.config.js file like this:

router: {
    scrollBehavior(to) {
      if (to.hash) {
        return {
          selector: to.hash,
          behavior: "smooth"
        };
      }
    }
  }

My 'pages' directory tree is like this:

pages/
   index.vue
   parent.vue
   random.vue

In default.vue of 'layouts' directory I wrote the navbar:

<button @click="$router.push({ name: 'parent' })">Parent One</button>
<button @click="$router.push({ name: 'parent', hash: '#sec2' })">Parent Two</button>

Inside parent.vue I have two sections:

<div class="sec-1" id="sec1">
      <h1>Parent One</h1>
      <p>...
      </p>
</div>
<div class="sec-2" id="sec2">
      <h1>Parent Two</h1>
      <p>...
      </p>
</div>

Now, The problem is When I click the 'parent two' button from random.vue file it doesn't work. but when I am in parent.vue file and click the button it scrolls to the second section. But I want to navigate to the second section from random.vue page. If I write the exact code in a vue project then it works fine but doesn't work in nuxt project. But I need to do it in my Nuxt project.

CodePudding user response:

Looking at my answer here, you can setup the following in a ~/app/router.scrollBehavior.js file

export default function(to, from, savedPosition) {
  console.log("this is the hash", to.hash)
  return new Promise((resolve, reject) => {
    if (to.hash) {
      setTimeout(() => {
        resolve({
          selector: to.hash,
          behavior: "smooth"
        })
      }, 10)
    }
  })
}

And it should work well. Maybe just silently fail when it does not find the selector or apply it only on specific paths.

  • Related