我通过向{API}发送response.data
请求从MongoDB获取数据。然后,我遍历response.data
并在每个nextArray
中遍历其属性,将我需要的数据推送到nextArray
。此schedulingQuality
应传递给Vuex中的methods: {
...mapActions(
['setSchedulingQuality']
),
get_data() {
const nextArray = [];
for(let i in this.SelectedtValues) {
axios.get('http://127.0.0.1:5000/getexp/'+this.SelectedtValues[i])
.then(res => {
for(let n in res.data) {
nextArray.push(res.data[n].output)
}
}
)}
console.log(nextArray);
},
computed: {
...mapGetters(
['schedulingQuality','selectedValues']
),
SelectedtValues() {
return this.$store.getters.selectedValues;
} ,
schedulingQuality() {
return this.schedulingQuality;
}
}
- 状态。这就是它的样子:
nextArray
当我打印出[]
时,似乎没问题。我在控制台上收到了i
,点击它后,会显示正确的内容,其中包含一个小Value below was evaluated just now
图标,上面显示“undefined
”。但是,当我尝试时,我无法单独打印出此数组的项目,每个项目的值都为Maximum call stack size exceeded
。
但我的主要问题是,当我试图将其传递到上面的代码中的Vuex状态时,它会抛出this.setSchedulingQuality(nextArray)
错误,因为打印出来,如:
import Vuex from "vuex";
import axios from "axios";
const createStore = () => {
return new Vuex.Store({
state: {
schedulingQuality: [],
},
mutations: {
SchedulingQuality(state, payload) {
state.schedulingQuality = payload;
}
},
actions: {
setSchedulingQuality({commit}, payload){
commit('SchedulingQuality',payload)
}
},
getters: {
schedulingQuality(state) {
return state.schedulingQuality;
}
}
});
};
export default createStore;
这是我的Vuex代码:
{{1}}
我的问题是:
答案 0 :(得分:1)
axios
调用是异步的。在您致电console.log(nextArray)
时,axios功能尚未完成。这就是为什么你得到空数组的原因。
您异步调用多个api,我建议您查看Promise.all
get_data() {
const nextArray = [];
Promise.all(this.SelectedtValues.map(value => {
return axios.get('http://127.0.0.1:5000/getexp/' + value)
})).then(results => {
results.map(res => {
for(let n in res.data) {
nextArray.push(res.data[n].output)
}
})
console.log(nextArray);
}).catch(err => {
console.error(err)
})
}