Skip to content Skip to sidebar Skip to footer

Vue Router - Change Anchor In Route On Scroll

I am basically trying to have the exact same routing behaviour on my site as here: https://router.vuejs.org/guide/#html. Notice when you scroll down the link changes to https://rou

Solution 1:

You could set up an IntersectionObserver and observe all sections on the page. When a section enters the view, take the section's id and update the route:

<div class="section" id="html">
  ...
</div>

<div class="section" id="javascript">
  ...
</div>
data () {
  return {
    sectionObserver: null
  }
},
mounted () {
  this.observeSections()
},
methods: {
  observeSections() {
    try {
      this.sectionObserver.disconnect()
    } catch (error) {}

    const options = {
      rootMargin: '0px 0px',
      threshold: 0
    }
    this.sectionObserver = new IntersectionObserver(this.sectionObserverHandler, options)
  
    // Observe each section
    const sections = document.querySelectorAll('.section')
    sections.forEach(section => {
      this.sectionObserver.observe(section)
    })
  },
  sectionObserverHandler (entries) {
    for (const entry of entries) {
      if (entry.isIntersecting) {
         const sectionId = entry.target.id
         // Push sectionId to router here 
         this.$router.push({ name: this.$route.name, hash: `#${sectionId}` })
      }
    }
  }
}

As @Sigi mentioned in the comment, you can use this.$router.replace() instead of this.$router.push() in the sectionObserverHandler, to avoid cluttering the history.


Post a Comment for "Vue Router - Change Anchor In Route On Scroll"