`Vue Router - Dynamically update route anchor on scroll`

My goal is to achieve the same routing behavior on my website as demonstrated here: https://router.vuejs.org/guide/#html. If you observe, the link changes to https://router.vuejs.org/guide/#javascript when you scroll down, and reverts when scrolling back up. Additionally, the page retains your position even after reloading.

To implement a similar scroll behavior in my router, I have added the following code:

  scrollBehavior(to, from, savedPosition) {
    if (to.hash) {
        return { selector: to.hash }
    } else if (savedPosition) {
        return savedPosition;
    } else {
        return { x: 0, y: 0 }
    }

While I have managed to create links that direct to anchors and update the route accordingly, I am still puzzled on how to replicate the dynamic behavior observed on the Vue Router website. It's a bit ironic that I chose their site as an example, but nonetheless, any suggestions on achieving this level of functionality?

Answer №1

To implement this functionality, you can utilize an IntersectionObserver to monitor all sections within the page. Upon detecting a section entering the viewport, extract its id and update the route accordingly:

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

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

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

Additionally, as suggested by @Sigi, consider using this.$router.replace() instead of this.$router.push() in the sectionMonitorHandler to prevent cluttering the navigation history.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to access the initial item in a JavaScript array?

Recently, I've been delving into the world of javascript and encountered a task that involves removing the first item from an array. Solution One function getFirst(arr, item) { arr.push(item); var removed = arr.shift(); return removed; } S ...

Switching out text when hovering with Jquery or JavaScript

Is there a way to use jQuery or JS to make the text and icon disappear when hovering over a div, and replace it with "Read More"? I've looked at some guides but they only remove one line of text instead of clearing the entire div and displaying "Read ...

Checking CORS permissions with a pre-flight OPTIONS request

During development, I implement a middleware called cors using the following syntax: app.use(cors({origin: 'http://localhost:8100'})); However, I have noticed that for every route request, two requests are being made as shown in the image below ...

What happens when the `.push` command runs the "Undefined" function in jQuery - is it possible to execute a number instead?

My script is quite simple - I'm trying to use the push method to add the result of a function called dNumber into the variable named pattern. However, every time I try this, the result is always "undefined". Oddly enough, when I try pushing just plain ...

Handling responses from http requests in Node.js

Below is the code snippet I am working with: exports.post = function(request, response) { var httpRequest = require('request'); var uri = "url.."; httpRequest(uri, function(err, responseHeaders, bodyResponse) { var data = JSON.parse( ...

Safari experiences occasional failures with pre-signed post uploads to S3 when using multipart/form-data for file uploads

Lately, I've encountered issues with pre-signed post uploads to S3 that seem to be unique to Mobile Safari browsers. Interestingly, the error has also shown up occasionally on Desktop Safari. Whenever this error occurs, it triggers a response from S3 ...

Vue - Troubleshooting why components are not re-rendering after data updates with a method

Check out this simple vue component I created: <template> <div class="incrementor"> <p v-text="counter"></p> <button v-on:click="increment()">Increment</button> </div> </template> <script lan ...

axios interceptor - delay the request until the cookie API call is completed, and proceed only after that

Struggling to make axios wait for an additional call in the interceptor to finish. Using NuxtJS as a frontend SPA with Laravel 8 API. After trying various approaches for about 4 days, none seem to be effective. TARGET Require axios REQUEST interceptor t ...

Obtaining the pathname in a NextJS file like _document.js is a matter of accessing

I'm looking to retrieve the current URL path in my /page/_document.js file. I've created a class and my goal is to implement a conditional statement based on this value. Below is the code snippet (similar to the example provided in NextJS docume ...

RxJS: Transforming an Observable array prior to subscribing

I am retrieving data (students through getStudents()) from an API that returns an Observable. Within this result, I need to obtain data from two different tables and merge the information. Below are my simplified interfaces: export interface student Stude ...

What could be causing the issue with the computed property not functioning correctly as the v-model on the Vuetify date

When working with Vuetify's v-date-picker, I customized a reusable component and implemented props to allow the parent component to set the value in the child component. To enable changes to these props, I created a computed property in the child comp ...

What is the distinction between declaring a variable as var $a=$() versus var a?

In some cases, in JQuery we assign a variable like var $a=$(), resembling the declaration of a function. I am curious to know if there is any difference if we simply define the variable as var a? ...

When touch-triggered on IOS, HTML5 Web SQL Transactions were smoothly bypassed without any errors

I'm encountering issues with database transactions on IOS devices. When the user does not interact with the phone, everything functions as expected. However, if the user taps, scrolls, or touches the screen, some transactions bypass the actual transac ...

How can I modify the text that appears when hovering over an element?

Can the displayed text be altered on mouse hover? For instance, can I change the text of a H1 tag when hovering over it using HTML, CSS, and JavaScript? ...

Using Puppeteer and Scrapy, this innovative Web Crawler with Scraper combines the power of both

As a newcomer to web technologies, I am faced with the task of crawling and scraping numerous websites that utilize a combination of React, JavaScript, and HTML. These sites collectively contain approximately 0.1 to 0.5 million pages. My plan is to use Se ...

Verify if the property in every element of the array is not empty

How can you determine if all employees have a non-null value for the SSN property in the given object? Employees: { id: 0, name: "John", SSN: "1234" } { id: 1, name: "Mark", SSN: "1876" } { id: 2, name: "Sue&q ...

The $or operator in mongoose falls short in providing complete data when paired with the find() method

I am currently utilizing the find method in conjunction with the $or operator to search the database for any duplicate data within this specific line. const duplicate = await NewItemsData.find({ $or: newItems }); Upon inspecting the variable in the consol ...

1. Catalog of dual JSON inquiries2. Compilation of

I am struggling to understand the right way to proceed. When I run this query, I receive a JSON response containing file names: $.getJSON("http://api.server.com/my/?callback=?", function(data){ var results = []; $.each(data['resul ...

Utilize Node.js v16 for the execution of chaincode operations

Currently, I am executing JavaScript/TypeScript chaincode from fabric-samples (asset-transfer-basic/chaincode-javascript) and my requirement is to switch the Node.js version from 12 to 16. I suspect that the hyperledger/fabric-nodeenv image is specifying ...

Tips for linking weight scale device to a website

I recently developed a web application that calculates the weight of products. The application was created using PHP, JavaScript, and AJAX, running on a XAMPP server. Now my client is requesting for me to integrate a weight scale machine into the applica ...