gridsome / gridsome

⚡️ The Jamstack framework for Vue.js
https://gridsome.org
MIT License
8.53k stars 490 forks source link

Deeplinking to #ID #1309

Open theisws opened 4 years ago

theisws commented 4 years ago

Hey guys!

Is there anyway you can deeplink to #ID's, using url like www.mypage.com/section2. The goal i that the URL will go directly to the "<div id='section2'<...</div<" scrolling past "section1". When I try, it hit the 404-error site. And i cant manage to find a way?

/Theis

cco3 commented 4 years ago

Is there anything wrong with using www.mypage.com/#section2? If so, yes you can link to that.

If it doesn't work, you may have to modify router.options.scrollBehavior in main.js.

export default function (Vue, { router }) {
  // Overwrite the router options.
  router.options.scrollBehavior = async (to, from, savedPosition) => {
    if (to.hash) {
      if (from.path !== to.path) {
        await new Promise(resolve => {
          // This event is emitted by App.vue.
          router.app.$el.addEventListener('routeEnter', resolve, {
            once: true
          })
        })
      }

      const elem = document.querySelector(to.hash)
      if (elem) {
        const offset = parseFloat(getComputedStyle(elem).scrollMarginTop)
        return {
          selector: to.hash,
          offset: { y: offset }
        }
      }
    }
    if (savedPosition) return savedPosition
    return { x: 0, y: 0 }
  }
}