Vue数据不在控制台上显示值,但会在组件上显示

问题描述 投票:0回答:3

我正在尝试检索全局会话值并将其设置为vue变量。问题是,id变量没有在控制台上显示任何值,但确实在vue组件上显示了值。我已经检查了vue devtools并且id确实包含正确的值。

组件视图

<template>
  <div class="container">
    <h1>{{id}}</h1> // the id does displays the value
  </div>
</template>

<script>
export default {
    data () {
        return {
          id:'',
        }
    },
    created(){
        axios.get('api/studentlecture').then(response => this.id = response.data).catch(function(error){console.log(error)
        });     
        console.log(this.id) 
    },
    methods:{

    },
    mounted() {
        console.log('Component mounted.')
    }
}

调节器

public function index()
{
    $id= session('userID');
    return json_encode($id);
}
php laravel vue.js artisan
3个回答
3
投票

因为axios调用是异步的。 JavaScript引擎将执行axios请求,在等待时它将继续执行代码。

您正在尝试记录尚未分配的this.id。如果要记录该值,则必须将其置于axios函数的回调中。

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

1
投票

发生这种情况是因为console.log(this.id)axios.get()解决它的承诺之前执行。

有一些解决方案。

第一个是在console.log()内移动then()

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

或者你可以利用async/await等待承诺解决

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)
  }
}

您可以了解更多有关承诺here的信息

更多关于async / await与promise here的区别


0
投票

您可以尝试使用以下代码:

/*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);
 }
© www.soinside.com 2019 - 2024. All rights reserved.