【发布时间】:2020-03-23 22:10:20
【问题描述】:
我试图在 Vue.js 中的另一个函数之后执行一个函数。我已经尝试过异步/等待、回调函数、.then,但它不知何故不想一个接一个地加载。什么是可能的解决方案?
auth_mixin.js:
async auth () {
console.log("authban")
var token = this.getCookie("token")
var jsonData = {}
jsonData["token"] = token
console.log(jsonData)
var bodyFormData = new FormData();
bodyFormData.append('data', JSON.stringify(jsonData));
axios({
method: 'post',
url: 'backend/index.php?action=checkAuth',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function (response) {
console.log(response);
if(response.data.status==="OK"){
console.log("ok")
return true;
}else{
console.log("nem ok")
return false;
}
})
.catch(function (response) {
console.log(response);
return false;
});
}
Navbar.vue:
created () {
var result=false
this.auth().then(this.checkIfLoggedIn(result))
},
methods: {
checkIfLoggedIn (isLoggedIn) {
console.log("na ez lesz az erdekes "+isLoggedIn)
if(isLoggedIn === true){
console.log("true")
document.getElementById("logged_out").style.display="none";
document.getElementById("logged_in").style.display="block";
}else{
console.log("fail");
}
}
}
【问题讨论】:
-
第一个明显的问题...问题,
.then需要一个函数作为参数,其他任何东西都被忽略(在这种情况下立即执行)-另一个问题,为什么使用var result = false并通过 @987654327 @ 到this.checkIfLoggedIn而不仅仅是this.checkIfLoggedIn(false)- 因为这是你的代码唯一能通过的东西
标签: javascript vue.js asynchronous promise callback