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

Elements in Motion

Working on a parallax effect, I've managed to assign unique scroll speeds to (almost) every element. Moreover, these elements are programmed not to activate their scroll speed until they enter the viewport. Below is the JavaScript code for trigger co ...

Sorting table tbody elements created dynamically with JavaScript on an npm webpack application is not possible with jQuery UI

My JS-built table is populated with data from a JSON file fetched after a request. I want to be able to drag and drop these tbodys and update the JSON file accordingly. To handle sorting, I decided to use jquery-ui. While .sortable() works well for drag a ...

Using the `ssh2` module in Node.js without specifying a specific object

When you use require('ssh2') in Node.js without a specific object (e.g. require('ssh2').Client), what does it imply? I'm in the process of understanding some code and still new to learning Node.js. Here's how it is being used: ...

What could be the reason for v-model not functioning properly?

Embarking on my Vue.js coding journey, I am currently following a straightforward online tutorial. Utilizing the vue-cli, I kickstarted my application and crafted a basic component named Test.vue. Within this component lies a simplistic input control conne ...

"Looking to replace a character class pattern using regex in JavaScript? Here's how you can easily

I have a string: "\W\W\R\" My goal is to transform this string using regular expressions into: <span>W</span><span>W</span>\R This is the code I'm currently using: "\W\W\R".replace(/&b ...

Gain access to Google Analytics without the need for page consent by utilizing JavaScript

I am currently building a dashboard with Atlasboard. My goal is to retrieve Google analytics data such as page views, and I plan to run specific queries which can be found here. Is there a method to access my Google analytics data without the consent pag ...

I am looking to gather user input in JavaScript and then showcase that input on the webpage. What would be the best

I am currently learning Java and I decided to challenge myself by creating a hangman game. The issue I am facing is that when the user inputs a letter, nothing happens - there is no output indicating whether the guess was correct or incorrect. I suspect th ...

The input box refuses to accept any typed characters

I encountered a strange issue where the input box in the HTML was not allowing me to type anything. const para = document.createElement('p') const innerCard = document.getElementsByClassName('attach') for(let i = 0; i < innerCard.l ...

Transmit data in the form of a buffer

const response = await client.render(data); const Writable = require('stream').Writable; var buffer = []; const myWritableStream = new Writable({ write(chunk, encoding, callback) { ...

What is the best way to access a Python API or local data within the Google Visualization DataTable JavaScript library?

I have been tirelessly working for the past two weeks to figure out how to load a local CSV file into google.visualization.DataTable() or use Ajax to call a Python Flask API that I created. My ultimate goal is to dynamically create a Gantt chart. Here&apo ...

The ajax success error function does not trigger in jQuery

Hey, check out my code below: <html> <head> <script src="http://code.jquery.com/jquery-1.8.0.min.js"> </script> </head> <body> <form id="foo"> <label for="bar">A bar</label> <input id ...

Using Heroku to deploy NodeJS applications

I am facing an issue while trying to deploy my NodeJS project on Heroku. The project is a multiplayer game where, locally, both players enter the same map successfully. However, on Heroku, I am unable to get both players on the same map. Below is a snippe ...

Troubleshooting: Resolving the Issue of Undefined Property Reading Error

I am currently working on a code snippet to render filtered data: const tasks = [{ task: "Complete homework", description: "Math and Science assignments." }, { task: "Walk the dog", description: "Take him for a stroll in the park." }, { ...

Why is the "class" attribute of an SVG node not being applied when I change it?

I am having trouble changing the "class" attribute of a node in SVG using my AngularJS Directive. Even though I've written the code to do so, it doesn't seem to be applied properly. This is the code snippet from my Directive: node = node.data(f ...

How to Redirect a Webpage to the Same Tab in ASP.NET

I am currently using an asp.net hyperlink control to direct users to a web URL when the hyperlink is clicked. My goal is for the user to open a new tab, rather than a new window, when they click the hyperlink. If the user clicks the link again, I want th ...

Sharing data between pages in Ionic and Angular with POST requests

Currently, I am utilizing Ionic for developing a mobile application and have decided to incorporate very basic authentication (without any security measures) into the app. The process involves validating user credentials against a database through a POST r ...

Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below ...

The Next.js app's API router has the ability to parse the incoming request body for post requests, however, it does not have the

In the process of developing an API using the next.js app router, I encountered an issue. Specifically, I was successful in parsing the data with const res = await request.json() when the HTTP request type was set to post. However, I am facing difficulties ...

Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data. When I try to directly set the values, I get an undefined result. So I created a variab ...

React/Redux - Issue with rest operator functionality in component

Here is the initial state I am working with: const initialState = { selectedGroup: {}, groups: { rows: [], total: null }, offset: 0, range: 15, loading: false, error: null } Within a reducer function, I have this case for successful ...