How to create anchor tags with Vue Router

前端 未结 4 1993
半阙折子戏
半阙折子戏 2020-12-15 06:45

I am creating a small Vue webapp, I want to create an anchor tag in this.

I have given an id to one of the div I wanted to have anchor tags

4条回答
  •  孤街浪徒
    2020-12-15 07:14

    For me the {selector: to.hash} solution just refused to work with vue-router 4.0.0. The following approach worked and also enabled smooth scrolling.

    The timeout of 500ms is there to allow the page to load, because I found that otherwise smooth scrolling would not scroll to the correct position (because the page was still loading).

    const scrollBehavior = (to, from, savedPosition) => {
      if (to.hash) {
        setTimeout(() => {
          const element = document.getElementById(to.hash.replace(/#/, ''))
          if (element && element.scrollIntoView) {
            element.scrollIntoView({block: 'end', behavior: 'smooth'})
          }
        }, 500)
    
        //NOTE: This doesn't work
        return {selector: to.hash}
      }
      else if (savedPosition) {
        return savedPosition
      }
      return {top: 0}
    }
    

提交回复
热议问题