Search code examples
vue.jsvuejs3vue-router

Vue router params undefined


i use this code

Hi guys i use this code for a simple route param but somehow i get an undefined in the url

 const router = useRouter();
  const navigateToQuiz = () => {
    router.push(/quiz/${quizcard.id});
  };

  const quizcard = ref([
    {
      id: 1,

    }

, router file

  {
      path: "/quiz/:id",
      name: "quiz",
      component: QuizView,
    }, 

I use navigateToQuiz in a list

   <li
            @click="navigateToQuiz"
            v-for="quiz in quizcard"
            :key="quiz.name"
            class="col-span-1 flex flex-col divide-y divide-gray-200 rounded-lg bg-white text-center shadow"
          >

Solution

  • In your code you need to write quizcard.value first because you are using a ref. Then to access the id, since it’s an object in an array, get the object by index then you can access the id property: quizcard.value[0].id

    Also make sure you use backticks.

    EDIT Based on what you are trying to achieve it looks like this is the right implementation

    
    const router = useRouter();
    
    const navigateToQuiz = id => {
     router.push(`/quiz/${id}`);
    };
    
    const quizCards = ref([{ id: 1 }, { id: 2 }])
    
    // refs are unwrapped in template so you dont need .value here
    <li v-for="quizCard in quizCards">
      <button @click="navigateToQuiz(quizCard.id)">click me</button>
    </li>