Navigating to the same hash using Vue Router in a consecutive manner

Currently, I am developing a website using Vue and Vue Router for routing. The method I am using to manage scroll behavior for anchor links is as follows:

const router = new VueRouter({
    routes,
    scrollBehavior (to) {
        if (to.hash) {
            return { 
                selector: to.hash,
                offset: { x: 0, y: 140 }
            }
        }
        return { x: 0, y: 0 }
    }
})

My anchor links are created like this:

<router-link class="insurance-link d-block" to="#hogar">
    <img class="insurance-logo img-fluid" src="@/assets/home-icon.svg">
    Hogar
</router-link>

When I click on the link for the first time, it scrolls to the anchor position correctly. However, when I scroll back to the top and click on it again, it does not scroll back to that position. Interestingly, if I click on another anchor link and then click on the previous one, everything works as expected. Any insights on what might be causing this issue?

Answer №1

To simplify things, consider using <a> instead

<a class="insurance-link d-block" href="#hogar">
    <img class="insurance-logo img-fluid" src="@/assets/home-icon.svg">
    Hogar
</a>

If you prefer using <router-link> and want it to function properly on the 2nd click, you will need to include a custom onclick handler like this:

<router-link class="insurance-link d-block" to="#hogar" @click.native="scrollToId('hogar')">
    <img class="insurance-logo img-fluid" src="@/assets/home-icon.svg">
    Hogar
</router-link>

Additionally, make sure to add the following code to your vue methods:

methods: {
  scrollToId(id) {
    document.getElementById(id).scrollIntoView();
  }
}

Answer №2

It appears that Vue is causing this behavior by stopping the click event from propagating. When you click on a hash that you are already on, the router sees it as no change and ignores it. The Vue documentation explains this as:

When using HTML5 history mode, router-link will intercept the click event to prevent the browser from reloading the page.

One way to have more control is to utilize the default slot of router-link. A workaround that seems to work is:

<router-link to="#hogar" v-slot="{ href }">
    <a :href="href">Hogar</a>
</router-link>

Answer №3

Building on Owl's solution, this code is designed to seamlessly integrate with vue-router version 4.4.x

const router = createRouter({/*...*/});

router.beforeEach((to, from, next) => {
    if(to.hash){
        document.querySelector(to.hash)?.scrollIntoView()
    }
    next()
})

Answer №4

Since my time was limited and I didn't want to keep experimenting with different solutions, I decided to go with the vue-anchor-router-link option (https://github.com/mperator/vue-anchor-router-link), and it worked perfectly. I am grateful to everyone for their contributions, as they helped me gain a better understanding of how Vue and Vue Router manage anchor links.

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

Creating a list of font sizes for each <p> tag in my HTML document

I am looking to create an array containing the font sizes of all the p tags in my HTML document. How can I specifically target only the p elements and not their parent elements? ...

Building a React component to display JSON data in a tabular format

I am trying to create something similar to the layout in the following link: Table example Imagine I have two arrays: names: ["Prisma 2 Case", "PP-Bizon", ...] imgs: ["img1.png", "img2.png", ...] One array contain ...

Navigate the Angular interceptor route to display a 404 error page when clicking on a `<a href="#">` tag

When using href="#" as a placeholder in html, I encountered an issue where Angular was unable to recognize it and would route to the 404 page despite having the following configuration in the module. How can this problem be resolved? .config( function m ...

Strategies for deactivating the next button when the input field is blank

I have been working on creating a multiple login form and everything was going well, but I am stuck on how to disable the next button if the email input is empty. The input has a class of "email" and the button has a class of "btn-next." Any assistance w ...

Combining items from the identical array in pairs using distinct identifiers

I have an array containing double values. const data = [ -0.003,-8.178509172818559E-16, 0.002,-1.3576469946421737E-15, 0.007,-1.2329107629591376E-1] I am looking to utilize these values in react-vis. The necessary syntax for data insertion in react-vis ...

Encountered Runtime Error: TypeError - Carousel triggering issue with reading properties of null (specifically 'classList') in Tailwind Elements

Currently, I am encountering the error message: Unhandled Runtime Error TypeError: Cannot read properties of null (reading 'classList') while utilizing the Carousel component. The problem arises when I attempt to populate the carousel with images ...

Is there a way to automatically update the input value when I refresh the page following a click event?

Currently, I have multiple p elements that trigger the redo function upon being clicked. When a p element is clicked, the quest[q] template is loaded onto the .form div. These templates are essentially previously submitted forms that sent values to an obj ...

Having trouble with importing a TypeScript class: encountering a "cannot resolve" error message

Could you lend me your expertise? I'm puzzled by this issue that seems to be quite simple and straightforward: export class Rectangle { height: number = 0 width: number = 0 constructor(height: number, width: number) { this. ...

use dotenv in your Build Folder

Is it possible to have my .env file in my React JS project move to the build folder when I run NPM build command? If so, how can this be achieved? If not, what would be the alternative solution? I attempted using "build": "cp .env.template ...

Is there a way to resolve the error message type issue in Quasar Vuelidate?

I'm utilizing the "vuelidate" plugin for validating the Quasar framework. After writing the code below, I encountered a type error. (property) error-message: string | Ref Type 'string | Ref' cannot be assigned to type 'string | undefi ...

Receiving the [object HTMLInputElement] on the screen rather than a numerical value

I have an input box where a user can enter a number. When they click a button, I want that number to be displayed on the page. However, instead of seeing the number, I am getting the output as [object HTMLInputElement]. Below is my TypeScript code: let qu ...

Converting JSON object to a string

I have an object that contains the value "error" that I need to extract. [{"name":"Whats up","error":"Your name required!"}] The inspector displays the object in this format: [Object] 0: Object error: "Your name required!" name ...

Numerical values are not considered by the JavaScript table filter

I'm having trouble with dynamically filtering the content. It works fine for the first two columns, but not for the third one. Maybe I need some additional JavaScript? Here is the link to my snippet: `https://www.w3schools.com/code/tryit.asp?filen ...

Generate visual at reduced quality (three.js)

Is there a way to reduce the resolution of my rendered canvas similar to how it can be done with the Blender camera resolution? I came across a suggestion to use renderer.setDevicePixelRatio(window.devicePixelRatio) However, when I tried this, the objec ...

dividing values for future angular use

Within my code, I have the following snippet: color: {{item.color}} This setup functions well when dealing with single items. However, there are instances where I encounter a value such as: white|black Is there a way to separate these values into indiv ...

Setting a bookmark feature in HTML using localStorage: A step-by-step guide

I'm working on a simple code that captures the text content of a dynamically updated <h1> element and stores it as a "bookmark" in localStorage. I want to enable users to save or delete the bookmark by clicking a button. Below is a basic version ...

While utilizing the Vue-Router, an error message may appear: "Vue warn - Failed to mount component because the template or render function is

I'm new to Vue and I'm using the Vue router. I encountered the error shown below, and I suspect it may be authentication-related. What are your thoughts? Here are my Routes: import Vue from 'vue'; import Router from 'vue-router&a ...

Stop ajax request when select2 is clicked

Is there a way to change the ajax call behavior in select2 drop down items so that it only retrieves data when I start typing in the search box, and not on click of the element? Your guidance on this issue would be highly appreciated. $("#ddlItems").sel ...

Refresh a dynamically loaded webpage following an update

Trying to grasp the concept of reloading a dynamic page loaded with AJAX after a record is updated. Here's the jquery script on the page: <script type="text/javascript> function showUser(str) { if (str == "") { $("#txtHint").empty() ...

Failed jQuery AJAX request to database with no returned information

I'm really confused about where the issue lies :S The button triggers a function that passes the parameter "sex" and initiates an ajax call to ajax.php, where I execute a MySQL query to retrieve the results and populate different input boxes. When I ...