【发布时间】:2021-04-18 19:41:10
【问题描述】:
如果这个问题已经在某个地方解决了,我很抱歉,但我无法理解我的问题是什么。在我的场景中,我想在页面最终呈现之前进行 2 个 axios 调用并使用这两个数据响应做一些事情。如果我在模板中输出数据,它是可见的,但是当我想在呈现页面之前使用它时,该值始终是未定义的。 经过一番研究,我想出了以下解决方案:
created() {
this.getStuff()
},
methods: {
async getStuff(){
this.Stuff1= await this.getSomething1()
this.Stuff2= await this.getSomething2()
var test = this.Stuff1[2].name
console.log(test)
},
async getSomething1(){
const response=await axios.get('http://localhost:4000/apiSomething1');
return response.data;
},
async getSomething2(){
const response=await axios.get('http://localhost:4000/apiSomething2');
return response.data;
},
}
如果我想对这些值做一些事情,例如将它传递给另一个值,它将无法工作,因为 Stuff1 是未定义的。为什么会这样?据我了解,由于await,异步函数应该等到promise 完成,所以在getStuff() 中的2 等待之后,该值应该存在,但事实并非如此。非常感谢您的帮助!
编辑 我尝试了提到的两种解决方案,但遇到了同样的错误。为了清楚起见,我添加了整个代码。
<template>
<h3>List all players</h3>
<br />
<table>
<tr v-for="player in PlayerAll" :key="player._id">
<td>{{ player.lastname }}</td>
<td>{{ player.name }}</td>
<td>{{ player.birthdate }}</td>
<td>{{ player.hash }}</td>
<td>
<Button
@click="deleteSpieler(player._id)"
class="p-button-danger"
label="Delete Player"
/>
</td>
</tr>
</table>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
PlayerAll: [],
TeamAll: [],
Combined: [],
};
},
async created() {
await this.fetchData();
var test = this.TeamAll[2].name;
console.log(test);
},
methods: {
async fetchData() {
let requests = [];
try {
requests = await axios.all([
axios.get("http://localhost:4000/apiPlayer"),
axios.get("http://localhost:4000/apiTeam"),
]);
} catch (e) {
console.error(e);
}
this.PlayerAll = requests[0].data;
this.TeamAll = requests[1].data;
},
},
};
</script>
<style scoped>
.btn-success {
width: 150px;
height: 150px;
background: red;
}
</style>
【问题讨论】:
-
我不知道你在 vue 中一般是如何设置状态的,但只是看看你获取数据的方式,它应该是正确的。
-
所以我必须为此使用状态管理?我只在传递响应的数据属性中声明了 2 个数组
-
我认为您还需要在 created() 方法中等待 this.getStuff()。
标签: javascript vue.js axios