gpt4 book ai didi

javascript - 计算函数返回空 - 获取问题?

转载 作者:行者123 更新时间:2023-12-04 08:01:10 26 4
gpt4 key购买 nike

我是 JS(和 vue 也是)的新手,并且在获取数据时遇到问题。我的目标是 - 想要保存 API 中的所有数据并在函数中使用它们。
代码:

<div>{{ dotToComma }} kg</div>
View :
export default {
data() {
return {
weight: null
};
},

created() {
this.api();
},

methods: {

//this is working correctly
async api() {
const api = await fetch("/reporting/patient/values");
const data = await api.json();
this.weight = Math.round(data.weight * 10) / 10
}
},

computed: {
//this.weight is still null
dotToComma() {
return this.weight.replace(".", ",");
}
}
};
问题出在哪儿?谢谢
更新:
dotToComma 中的函数替换仅适用于字符串,因此您必须添加 toString() 函数:
return this.weight.toString().replace(".", ",");

最佳答案

异步函数不会立即给你结果,所以你需要检查你是否有 this.weight , 或不。 Computed 将使用新值,当它出现时。
您可以阅读有关 JS 异步实现的更多信息 here

关于javascript - 计算函数返回空 - 获取问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66455258/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com