我正在尝试检索全局会话值并将其设置为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);
}
因为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)});
发生这种情况是因为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的区别
您可以尝试使用以下代码:
/*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);
}