我想更新我的变量 nbeBugs 但在 then 函数内无法访问。
我的函数 getApi 是 async 函数,因为 API 需要时间响应
Nombre de bugs Gitlab
import axios from "axios";
let path = import.meta.env.VITE_API_URL;
const axiosObjet = axios.create({
baseURL: path,
timeout: 8000,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.apiToken
}
});
async function getApi(api_path, data) {
//console.log(headers)
console.log(path)
//console.log(axiosObjet)
try {
let res = await axiosObjet.get(api_path)
if(res.status == 200){
// test for status you want, etc
console.log(res.status)
}
// Don't forget to return something
return res
}
catch (err) {
console.error("getApi error : " + err);
}
}
export default getApi Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果传递给
.then()函数的参数是常规函数,它有自己的作用域,并且在其内部,外部作用域的变量将无法使用this 访问..改用箭头函数 :
getApi(url_application, null).then(({ data }) => { console.log(data); this.nbeBugs = data; });旁注:您将在请求返回之前更新
this.chartGitlab。要么将该更新移至then()内,要么在服务器请求前面使用await。最有可能的是,这将按预期工作:methods: { async getData() { let url_application = "api/bugs_gitlab"; await getApi(url_application, null).then(({ data }) => { console.log(data); this.nbeBugs = data; }); this.chartGitlab = { labels: ["Bloquant", "Critique", "Majeur", "Moyen", "Faible"], datasets: [ { borderColor: "#071426", data: this.nbeBugs, backgroundColor: ["#FF6384","#36A2EB","#FFA726","#66BB6A","#a855f7"], hoverBackgroundColor: ["#FF6384","#36A2EB","#FFA726","#66BB6A","#a855f7"], }, ], }; }, }