Change a Vue route parameter from title to id

As I develop a course website, each course is assigned its own page URL. For example, when accessing course number 1, the link appears as http://localhost:8080/course/1 . However, I aim to customize it to display as http://localhost:8080/course/course-name-here instead. My current challenge lies in updating the parameter without successfully retrieving data from the API.

index.js

{
    path: '/courses',
    name: 'Courses',
    component: () => import(/* webpackChunkName: "about" */ '../views/Courses.vue')
},
{
    path: '/course/:id',
    name: 'CourseDetail',
    props: true,
    component: () => import(/* webpackChunkName: "about" */ '../views/CourseDetail.vue')
}

CourseList.vue

<v-row>
   <v-col sm="6" md="4" v-for="course in courses" v-bind:key="course.courseId">
      <router-link v-bind:to="{name: 'CourseDetail', params: {id: course.courseTitle}}" class="text-decoration-none">
         <VerticalCard v-bind:course="course"/>
      </router-link>
   </v-col>
</v-row>

CourseDetail.vue (script)

import axios from 'axios'
export default {
  props:['id'],
  data: function(){
    return {
      singleCourse: null,
      selectedIndex: null,
      showPage: false
    }
  },
  methods: {
    getData() {
      var that = this
      axios.get('http://my-api-here.amazonaws.com/v1/api/course?id=' + this.id,
            {
              headers: {
                'Authorization' : 'Bearer ' + this.$store.state.authKey 
              }
            })
            .then(function(response) {
              that.singleCourse = response.data.body
            })
      },
      show() {
        if(this.$store.state.isLogin == true){
          this.showPage = true
        }
        else {
          this.$router.replace('/login')
        }
      }
  },
  mounted: function() {
    this.getData()
    this.show()
  }
}

example of a singleCourse

{ "_id": { "$oid": "5fc63dab36d8491476999831" }, 
"courseTitle": "Python For Everybody", 
"createdDate": { "$date": 1606852635135 }, 
"creator": "Admin", 
"courseId": 1, 
"courseDesc": "Description Lorem Ipsum is simply dummy text of the printing", 
"courseCategory": "Programming", 
"courseImage": "https://cwpwp2.betterthanpaper.com/wp-content/uploads/2019/06/2-1-1.jpg", 
"syllabus": [ { "chapterName": "Introduction to Python 3 Programming Tutorial", "chapterVideo": "eXBD2bB9-RA" }] }

Answer №1

Utilize an object to find each course's identification number based on its name. Instead of using the id, use the title parameter (update it in the route, link, and prop). Within the component:

data() {
  return {
    courseIds: {
      'course-name-here': 1,
      'other-course': 2,
      'one-more': 3
    }
  }
}

Implement this within getData():

getData() {
   ...
   const url = 'http://my-api-here.amazonaws.com/v1/api/course?id=';
   axios.get(url + this.courseIds[this.title])
   ...
}

If other modules or components require access to this data, you could store the lookup data in Vuex instead.

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

Instructions for displaying a React component in the <main> element when employing react-burger-menu

Check out my code here. Utilizing react-burger-menu has allowed me to successfully implement the sidebar feature. The sidebar functionality is working as expected. My current challenge involves figuring out how to open the content for Home or GG within ...

Comparison of Types using Strings

Is there a simpler way to solve this problem? My goal is to compare a string value with a defined type. The type I have looks like this, and I receive a string value from an API request. type stringTypes = 'abc' | 'asd' const testVal ...

What is the best way to display a child component inside an iframe using Vue.js?

Looking to provide a live preview of an email before sending it out, I've opted to use an iframe to contain the preview and prevent style leaks. The goal is for the preview to update dynamically as the user fills out form details. How can I display a ...

A guide on unpacking errors returned from a backend and sent out as an Error object in JavaScript

After investigating, it turns out that the issue lies with how the Error object constructor handles the response object passed to it in the catch error handler. The SDK I am using contains a method which can be found at this link to sdk code /** ...

Is a Promise nested within another Promise?

My current task involves retrieving the lat/long of 2 addresses using promises. Once this initial promise is resolved, I need to parse a file that correlates with these lat/long coordinates. Everything works as expected and I can handle the values in the ...

What is the best way to eliminate additional values depending on the one I have chosen?

When utilizing the Vuetify v-autocomplete component with the multiple prop, we are able to select multiple values. How can I deselect other values based on the value I have selected? For instance: If I choose the main value, all others will be deselecte ...

Frustratingly Quiet S3 Upload Failures in Live Environment

Having trouble debugging a NextJS API that is functioning in development (via localhost) but encountering silent failures in production. The two console.log statements below are not producing any output, leading me to suspect that the textToSpeech call ma ...

Execute the SQL "function" (or stored procedure?) whenever a database column is queried

Running on MySQL 5.6, I encounter a situation where various "name" columns in the database lack formatting and sanitization upon importation through CSV data dumps by customers each year. This results in names such as Phil Eaton, PHIL EATON, Phil EATON bei ...

What is the method for obtaining the object of the chosen Vuetify tab instead of its index value?

By default, the event triggered by changing the v-tabs provides the index of the new tab. However, I am encountering issues with obtaining the correct index when the tab items are dynamic. <v-tabs :slider-size=4 v-model="tabs" @change="tabChangeHandler ...

The inability to read property 0 of undefined persists despite implementing conditional rendering

I'm struggling to understand what mistake I'm making in the current situation: There's an array named arrayOfChildren that gets initialized like this: const [arrayOfChildren, setArrayOfChildren] = React.useState([]) With a handler function ...

React Component State in JavaScript is a crucial aspect of building

What happens when the expression [...Array(totalStars)] is used within a React Component? Is the result an array with a length of 5, and what are the specific elements in this array? We appreciate your response. class StarRating extends Component { ...

When using the require() function in Node.js, the period "." is not being recognized as part of the command and

I recently encountered a problem while working on my project and reorganizing my files. I noticed that the "." in my requires are not being parsed correctly. Upon running my program, an error message is displayed: Error: Module './src/map/createMa ...

React Timer App: The setInterval function is being reset after each render operation

I'm currently working on a straightforward timer application that will begin counting seconds when a button is clicked. To implement this, I am utilizing react hooks. import React, { useState } from 'react' function Timer() { const [sec ...

Inertia with Laravel appears to be triggering Vue components to load twice

After creating a Laravel project with Inertia and Vue, I encountered an issue where the code inside my Vue components is executed twice. To demonstrate this problem, I have created a Test.vue, containing the following code: <template> <div> ...

Element not recognized: <my-company-form-extra> - have you properly registered this component?

I've been attempting to render a component using the is directive <template> <div> <v-tabs v-model="currentTab" fixed-tabs> <v-tab v-for="(item, i) in tabItems" :key="i">{{ item }} < ...

Commit the incorrect file name with the first letter capitalized

There seems to be an issue with the git not recognizing the correct filename casing. I have a file named User.js in my workspace, but when checking the git status, it displays user.js instead. Despite repeatedly changing and committing as User.js, the gi ...

Avoid using single quotes in Postgres queries for a more secure Node.js application

Snippet from my node js code: var qry = 'INSERT INTO "sma"."RMD"("UserId","Favourite") VALUES (' + req.body.user + ',' + JSON.stringify(req.body.favourite) + ')' My problem is inserting single quotes before JSON.stringify(r ...

Mastering the usage of AngularJS Directive controllerAs syntax with scope is key to developing

I have included my code below: // HTML <body> <h1>{{foo.name}}</h1> <my-directive></my-directive> </body> // Scripts app.directive('myDirective', function() { return { restrict: 'E', ...

Rotating the camera around the origin in Three.js

Hey, I'm having some trouble with what I thought would be a simple task. I have a group of objects at the origin, and I'm trying to rotate a camera around them while always facing the origin. According to the documentation, this code should work: ...

How to transfer a user's comment from HTML to a C# model through a list within the MVC framework

I have been attempting various solutions, but none seem to be working. My goal is to create post and comment partial classes for a main page where end users can add comments. Currently, I am using MVC 5 and the page loads posts and previous comments. Howe ...