[Vuejs]-Vue data does not display value on console but does display on component

4👍

Because the axios call is asynchronous. The JavaScript engine will execute the axios request, and while it is waiting it will continue executing the code.

You are trying to log this.id while it has not yet been assigned. If you want to log the value, you have to put it in the callback of your axios function.

axios.get('api/studentlecture')
    .then(response => {
        this.id = response.data;
        console.log(this.id); // <== Here
    })
    .catch(function(error){console.log(error)}); 

2👍

This happens because console.log(this.id) is executed before axios.get() could resolve it’s promise.

There are a few solution for this.

First one is to move console.log() inside then().

created() { 
  axios.get('api/studentlecture').then(response => {
    this.id = response.data;
    console.log(this.id);
  }).catch(error => {
    console.log(error)
  });
}

Or you can make use of async/await to wait the promise to resolve

async created() { 
  try {
    // This will wait until promise resolve
    const response = await axios.get('api/studentlecture');
    this.id = response.data;
    console.log(this.id);
  } catch(error) {
    console.log(error)
  }
}

You can learn more about promise here

And more about async/await difference with promise here

👤Zendy

0👍

You can try using the following code below:

/*FRONT-END VUE*/

this.axios.get("https://localhost:8000/api/v1/data").then((response)=>{
                    this.data=response.data;
                    console.log(this.data);
                    if(this.data.success){
                      

                    }
 });
/*BACK-END LARAVEL*/
 
 function getData(){
    $result = array('success'=>true,'data'=>$data);
    
    return Response()->json($result);
 }

Leave a comment