Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Props gotten directly from vue 3 setup are not reactive

I am writing an application in vuejs and i want to pass prop to a child component but I am getting this error:

Getting a value from the props in root scope of setup() will cause the value to lose reactivity

Parent component

<template>
  <div>
      <course-list :courseId = "id"  />
  </div>
</template>
import {useRoute} from 'vue-router';
import { ref, onMounted, reactive} from 'vue';
export default defineComponent({
  components: { NavBar, CourseList, CourseContent },
  props:{
    courseId: String
  },
  setup(){
      const route = useRoute()

      const id = route.params.id
      console.log("the course id is", id);

    return{
      id
    }
  }
}

Child Component

export default defineComponent({
  components: { CourseTopic },
  props: {
      courseId: {
        type: String
      }
    },
  setup(props) {

    const trainingCourseId = props.courseId;

    return { courses, trainingCourseId };
  },
});

How do I solve this problem?

like image 516
etranz Avatar asked Aug 31 '25 15:08

etranz


1 Answers

Use toRefs() on props to keep the reactivity on the prop:

import { toRefs } from 'vue'

export default {
  setup(props) {
    const { courseId: trainingCourseId } = toRefs(props)
    return { trainingCourseId }
  }
}

Or toRef():

import { toRef } from 'vue'

export default {
  setup(props) {
    const trainingCourseId = toRef(props, 'courseId')
    return { trainingCourseId }
  }
}
like image 176
tony19 Avatar answered Sep 02 '25 21:09

tony19