Using props in BeforeMount or Mounted- VUE.JS

Viewed 1357

I have prop in child component -> kpi_kalite[]

Parent component-> mounted():

*(This kpi_kalite is created in parent component's data)

 axios.get(URL+ "/KPI/").then(response=>{

   console.log(JSON.parse(JSON.stringify(response.data)))

   this.kpi_kalite.push(response.data[0])

 })

I do 'get request' in parent componenet and i push the response.data to kpi_kalite[] (parent component)

And i use this array for props.

Then, I want to do console.log(this.kpi_kalite) in beforeMount or Mounted. But this props in not using.

 methods : {
     set_input(){

            console.log(this.kpi_kalite)
            for(const i in this.kpi_kalite){
                console.log(i)
                console.log(JSON.parse(JSON.stringify(this.kpi_kalite))) // output 
                                                                        //   "undefined"
       }
   }

},
beforeMount() {
    this.set_input()
}

console output : undefined

Could you help me? ,Before HTML-css loaded, I need parent component's data in child component

1 Answers

There is a post by LinusBorg about the order of lifecycle hooks for parent and child:

There’s nothing weird or wrong about it, it all follows from the lifecylce logically.

  • beforeCreate() and created() of the parent run first.
  • Then the parent’s template is being rendered, which means the child components get created
  • so now the children’s beforeCreate() and created() hooks execute respecitvely.
  • these child components mount to DOM elements, which calls their beforeMount() and mounted() hooks
  • and only then, after the parent’s template has finished, can the parent be mounted to the DOM, so finally the parent’s beforeMount() and mounted() hooks are called.

END

Also, there is a nice diagram here.

Child components are mounted before the parent component is mounted. Therefore, console.log(this.kpi_kalite) in the child component does not print the data gotten from the axios in the parent. So, if you do not render the child component at first, it will not be mounted because it is not created. If you render the child component after the axios is completed, it will be created and mounted. Then, console.log will print the value of kpi_kalite gotten from the axios in the parent.

ParentComponent:

<ChildComponent v-if="renderChildComponent" :kpi_kalite="kpi_kalite" />

data() {
   return {
      kpi_kalite: [],
      renderChildComponent: false,
   };
},
mounted() {
   axios.get(URL+ "/KPI/").then(response=>{
      console.log(JSON.parse(JSON.stringify(response.data)))
      this.kpi_kalite.push(response.data[0])
      this.renderChildComponent = true;
   })
},
Related