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 ofsetup()
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?
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 }
}
}