0

I assigned props to data in vue. But in created hook I am getting the values(group_id and subject_id) in data as undefined and that's why axios.post is giving me error. I found out that data function is called when vue instance is created, but there is still a little misconfusion. Is there any way to properly assign props to data so they can be used in created function?

props: ['name'], //props passed from route components
data:()=>({
 group_id: name.split("_")[1],
 subject_id: name.split("_")[2]
})
created(){
 console.log(this.group_id, this.subject_id) //log is giving me undefineds
 axios.post(`somelink`, { group_id: this.group_id, subject_id: this.subject_id })
}

1 Answers1

0

What you are trying to do is possible, but it is your code that has some problem. To access a props you need to use the this. So to access name in the data function you would do this.name.

This will still produce the undefined. This is because the scope of the this is not the correct one. The scope of the this is the vue component and should not be the scope from the caller. This means that you should not use a fat arrow function.

With these two corrections this would give the following code:

props: ['name'],
data(){
   return {
       group_id: this.name.split("_")[1],
       subject_id: this.name.split("_")[2]
   }
},
created(){
 console.log(this.group_id, this.subject_id)
 axios.post(`somelink`, { group_id: this.group_id, subject_id: this.subject_id })
}
Plpicard
  • 1,066
  • 6
  • 15
  • thank you for response, I've tried your suggestion and it worked. But I still have some misunderstanding, when I accessed props without `this` it assigned the values to data, but after created hook, I guess. Because in created hook `console.log(this.subject_id, this.group_id)` is giving me undefined but when I looked to the vue component through VUE devtools in browser it is assigned props to data – Shamsiddin Parpiev Jul 10 '20 at 17:19
  • After the vue template is parsed, the structure of the `this` is all changed. I am less experience with the exact details of how the devtool work. But I would suggest looking at this post to understand scoping of the `this`: https://stackoverflow.com/questions/48980865/vue-js-difference-of-data-return-vs-data. With a fat arrow the `this` scope calling point is what it is used and may be very different from the page and from the tool. – Plpicard Jul 10 '20 at 18:20