Luis
Luis

Reputation: 437

Vue - Issue with props filled using axios request

I have 3 vue components List, Car, AddNew

List.vue is the parent component and have 2 components like this:

<add-new :cars-models="carModels"></add-new>                

<car
 v-for="(car, index) in items"              
:key="car.id" 
:data="car" 
:car-models="carModels" 
>                   
</car>  

later it has this:

data(){

   return{
     items:'',
     carModels:''     
  }

}
,
created(){
     axios.get('car-models')
         .then(({data})=>{                              
            this.carModels= data;                           
        }); 

      axios.get('cars')
         .then(({data})=>{                  
            this.items = data;  
         });                    
}

In the addNew.vue I have this:

props: ['carModels'],
data(){
   return {
      models:''
   }
},
watch:{

        carModels(){
            this.models= this.carModels;
        }

    }

I had to use the watcher because carModels is filled in the parent component, is it ok here, but, in the Car.vue

props: ['carModels'],
data(){
   return {
      models:''
   }
},
watch:{

        carModels(){
            this.models= this.carModels;
        }

    }

As you can see, it is the same, but this.models is not filled with the prop carModels, despite the prop is filled!. I don't know what is happening. Thank you

Upvotes: 0

Views: 468

Answers (1)

Alvaro Ccatamayo
Alvaro Ccatamayo

Reputation: 331

My guess is that this is a timing issue. The watcher carModels isnt being triggered because the value for carModels is there since the creation of the component. What you can do is modify the data so it looks like this:

 return {
      models:this.carModels
   }

this way, the props data is copied at first, then updated by the watcher whenever the props is updated

props: ['carModels'],
data(){
   return {
      models:this.carModels
   }
},
watch:{    
        carModels(){
            this.models= this.carModels;
        }    
    }

Upvotes: 2

Related Questions