0

When I click an anchor with a href like this href='#title' I expect the page to scroll to the element that contains the id='title'.`

Instead it reloads the page and if I click it a second time only then it works. I am using vue-router and this is the router.options:

import type { RouterOptions } from '@nuxt/schema'

export default <RouterOptions>{
  strict: true,
  scrollBehavior: function (to, _from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else if (to.hash) {
      return {
        el: to.hash,
      }
    } else {
      return {
        left: 0,
        top: 0,
      }
    }
  },
}

1 Answers1

0

Hey i had the same Issue some weeks ago. Here is my solution:

import type { RouterConfig } from '@nuxt/schema'

// https://router.vuejs.org/api/#routeroptions
export default <RouterConfig>{
  scrollBehavior(to, from, savedPosition) {
    const nuxtApp = useNuxtApp()

    // If history back
    if (savedPosition) {
      // Handle Suspense resolution
      return new Promise((resolve) => {
        nuxtApp.hooks.hookOnce('page:finish', () => {
          setTimeout(() => resolve(savedPosition), 50)
        })
      })
    }
    // Scroll to heading on click
    if (to.hash) {
      setTimeout(() => {
        const heading = document.querySelector(to.hash) as any

        return window.scrollTo({
          top: heading.offsetTop,
          behavior: 'auto',
        })
      })
      return
    }

    // route change
    if (from.path !== to.path) {
      nuxtApp.hooks.hookOnce('page:finish', () => {
        window.scrollTo({
          top: 0,
          behavior: 'smooth',
        })
        return
      })
    }

    return { top: 0 }
  },
}
Bart
  • 515
  • 5
  • 12