首页 > 解决方案 > Getting NaN in URL even when right variable is passed via router-link

问题描述

I am using vue router-link to pass courseId and quizId to Quiz Component. When the Quiz component in initialized, it gets the courseId and quizId in the created() via this.$router.params. The params are obtained in the first attempt, but when I refresh the page, the quizId params is set to NaN. Also only the courseId is passed in the URL of the component whereas the quizId is NaN. I don't understand what exactly the problem is. I will post the code below.

routes:

const routes = [
  {
    path: '',
    component: Course,
    name:'ViewCourse'
  },
  {
    path: '/module/:course_id/:module_id',
    component: Module,
    name: 'ViewModule'
  },
  {
    path: '/:course_id/:quiz_id',
    component: Quiz,
    name: 'QuizModule'
  },
  {
    path: '/:course_id/:unit_id/:quiz_id',
    component: QuizInstructions,
    name: 'QuizInstructions'
  }
]

QuizInstructions:

     <router-link :to="{name: 'QuizModule', params: {course_id: courseId, quiz_id: quiz.id}}" class="btn btn-primary">Start Quiz</router-link>

Quiz:

created () {
    const courseId = parseInt(this.$route.params.course_id)
    const quizId = parseInt(this.$route.params.quiz_id)
    // This condition fails as quizId is NaN on page refresh
    if (courseId && quizId){
      this.fetchQuestions(courseId, quizId)
    }
  },

Please help me in understanding what I am doing wrong. This used to work before now it is breaking and I am unable to find the issue. Please tell me if more content is required. I have only posted the code which I think is causing the issue.

Thanks.

Edit: Issue resolved. I accidentally did router.push() in one of the vuex action which resulted in setting quizId as NaN. It was because I was pushing wrong undefined variable in the URL.

标签: javascriptvue.jsvuexvue-router

解决方案


推荐阅读