ella
ella

Reputation: 115

Convert Vue route param title to id

I'm creating a course website and each course has its own page. Let's say I open course number 1, then the link is http://localhost:8080/course/1 . I want to change it to http://localhost:8080/course/course-name-here . My problem is, when I change the param, the data isn't fetched 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" }] }

Upvotes: 1

Views: 243

Answers (1)

Dan
Dan

Reputation: 63059

Use an object to look up each course's id by the name. Pass the title param instead of id (change to title in the route, link, and prop). In the component:

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

Use this in getData():

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

You could keep the lookup data in Vuex instead if other modules / components need access to it.

Upvotes: 1

Related Questions