Is there a way to append a URL parameter after a link is clicked using Vue.js?

I am currently working on integrating heading links on my website's sidebar that are linked to the main content using scrollspy. This allows users to easily navigate to different sections of the main content by clicking on the corresponding headings in the sidebar. The challenge I am facing is how to dynamically update the URL when a user clicks on a specific heading, based on the data retrieved from a JSON file.

For example, let's consider the headings available in my JSON object:

  1. Heading 1
  2. Heading 2
  3. Heading 4

The goal is to update the current URL www.something.com to something like www.something.com/Heading1 when the user clicks on "Heading 1", and similarly for the other headings.

I am using Vue to implement this functionality, and below is a snippet of my code:

   <b-list-group-item :href="`#heading-${headingHash(headings.text)}`"> <--Reference to Heading.
              <span>
                <b>{{ index + 1 }}.</b> {{ headings.text }} <-- Heading Label.
              </span>
   </b-list-group-item>

If anyone has suggestions or tips on how to achieve this dynamic URL updating feature in Vue, I would greatly appreciate your assistance. Thank you!

Answer №1

If you are looking to implement navigation in your Vue.js project, consider utilizing Vue Router. By defining a click event function and leveraging Vue Router's programmatic navigation feature, you can easily navigate to the specific route you have in mind.

<template>
  <b-list-group-item
    @click="navigateToHeading(headings.text)"
    :href="`#heading-${headingHash(headings.text)}`"
  >
    <span>
      <b>{{ index + 1 }}.</b> {{ headings.text }}
    </span>
  </b-list-group-item>
</template>

<script>
export default {
  methods: {
    navigateToHeading(heading) {
      this.$router.push({
        path: `Heading${heading}`
      })
    }
  }
}
</script>

Answer №2

In order for the URL to be altered based on a href attribute, the use of an a tag is necessary.

Alternatively, it can be done through programming. Instead of inserting href into b-list-group-item, you could add a click event that would execute a function:

<b-list-group-item @click"changeURL(headings.text)">

The method could look something like this:

methods: {
    changeURL(text) {
      window.location.href = `#heading-${this.calculateHeadingHash(text)}`;
    }
}

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

Customize Your Greasemonkey Script Timeout

At our organization, we utilize the Firefox Greasemonkey addon to automatically enter login credentials on a specific webpage upon opening it. Here is an example of what the script consists of: // ==UserScript== // @name logon // @namespace http ...

Sorting through an array of JavaScript objects and aggregating the step values for matching user names

Currently, I am delving into JavaScript and facing a certain challenge that may be considered easier for seasoned developers. My goal is to iterate through an array of objects, filter out objects with the same userName, and then aggregate their steps. The ...

What is the most effective way to loop through an object containing DOM selectors as values, and subsequently utilize them to assign new values?

I have a function that takes an object retrieved from a database as its argument. My goal is to display the values of this object in a form by associating each value with a specific DOM selector. Here is the code snippet where I achieve this: function pai ...

What could be causing this JavaScript if statement to consistently evaluate to true?

I'm facing an issue where I want to run a specific block of code when a div is clicked for the first time, and then another block when it's clicked for the second time. The problem is that even though my alert shows the variable being updated wit ...

It appears that protractor-flake is programmed to re-run all tests instead of just the ones that have failed

Running tests using the latest version of "[email protected]", encountering failures during testing but the tests are rerunning again. No custom reporter used except Allure reporting. Below is the command used for running: protractor-flake --max-at ...

Displaying mysqli results within a div while incorporating an onclick event for a javascript function that also includes another onclick event for a separate javascript function

I'm struggling to figure out the correct way to write this script. Can someone please guide me in the right direction or suggest an alternative method? I've searched but haven't found any relevant examples. I am fetching information from a ...

jQuery: Managing and modifying values for dynamically generated input elements

Hello, I am currently working with the latest version of jQuery and have a table set up where clicking on the "Add" button appends a row of inputs. My goal is to calculate the total price for each particular product based on keyup events (i.e., qty * price ...

How can we bring in a JavaScript file to an Angular 2 project?

I've been struggling with importing a JavaScript file into my Angular2 project. This particular file is not a module from npm, and the usual instructions using npm don't apply in this case. My setup involves using Angular CLI, and within my angu ...

AngularJS: Move forward with controller execution after completion of a looped service method

Currently, I am implementing a networkService in Angular which is responsible for looping while the internet connection is unavailable. The goal is to resume execution once the connection is restored. Below is an example of a controller: MyApp.controller ...

Transitioning React Hover Navbar Design

I'm currently revamping a click-to-open navbar into a hover bar for a new project. I have successfully implemented the onMouseEnter and onMouseLeave functions, allowing the navbar to open and close on mouse hover. However, I am facing an issue with ad ...

Creating reactive Arrays in VueJSIn this guide, we will discuss methods

Struggling to implement a hover effect on images with Vue, specifically aiming to display the second item in an image array upon hover. The challenge is maintaining updated data in the templates when changes occur. Even attempted using Computed properties ...

Sketch a line extending from one element to the next

Is there a way to create a styled line that starts from the center of one <td> element and ends at the center of another? I attempted to use the jQuery Connections plugin but it only connects the edges of the elements, not their centers. The plugin ...

Is it possible to set all UI forms to a readonly/disable mode?

We have a specific requirement where, if the user's access level is set to "READ ONLY", all form input elements should be made readonly. Our coding approach involves using a template HTML that contains widgets which are referenced in the correspondin ...

The appearance of my website appears differently depending on the resolution

Just recently, I began exploring the world of HTML/CSS/JS and created a handy tool for my personal use. However, I encountered an issue when viewing it on different resolutions which caused some elements to look distorted. The tool I made allows me to inp ...

Is there a way to retrieve SQL information through an API and then incorporate that data into react-native-svg charts? I have an API that contains data I would like to retrieve and showcase

I am utilizing an API to retrieve data, which includes the execution of SQL queries. The API is responsible for fetching data and running these queries. I am looking for a way to replace the static data in my charts with dynamic data fetched from the API. ...

Using Spring MVC and Thymeleaf to dynamically load new HTML pages on ajax calls

Hello there, I'm looking to dive into using thymeleaf for my web application. My goal is to create a simple website with HTML pages. Below is the URL of my landing page controller that returns the index.html page: @RequestMapping("/index") public Str ...

testing express router with several different handlers

I have been testing my guard middleware and everything appears to be functioning correctly, but my expect statement is failing. /// auth.test.js const request = require('supertest'); const express = require('express'); const app = req ...

Executing a long job in PHP (Laravel) while simultaneously making an AJAX call

Looking to create a real-time progressing bar? I attempted to incorporate this example into my Laravel project but seem to have missed a step. Here is my HTML and JavaScript code: <div style="border:1px solid black;width:500px;height:80px"> &l ...

Showing a dynamically updated array in Angular

Within my Angular Application I am utilizing an ngFor loop in the component to display an array. Now, I am filtering the data from the array and aiming to update the newly filtered array in place of the original one. While I can successfully display the ...

Problem with BeforeRouteEnter causing failure to populate data in variable

After setting up a web API that successfully sends data, I encountered an issue with my Vuejs app's data table component. Even though I made an API call using Axios within the BeforeRouteEnter hook, the data from the response doesn't seem to save ...