【发布时间】:2024-10-08 06:50:02
【问题描述】:
在一个名为 GlobeInformation.vue 的 VueJS 组件中,我想调用一个 getter “mapData”,我希望它返回我的状态数据的操纵版本,但是当我在我的模板中显示它时它显示为一个空数组。我在下面发布了我的代码的精简相关版本。提前致谢。
PS:我想这是由于异步 API 调用而发生的,因此我尝试使用 v-if 条件来检查是否已收到数据,然后才将其呈现在模板上。
GlobeInformation.vue
<template>
<div class="information">
<div v-if="mapDataLoaded">
{{ mapInformation }}
</div>
</div>
</template>
<script>
export default {
data: function() {
return {
mapDataLoaded: false,
mapInformation: []
}
},
computed: {
...mapGetters(['mapData'])
},
methods: {
...mapActions(['fetchCondensedDetails'])
},
async mounted() {
await this.fetchCondensedDetails('/')
this.mapInformation = await this.mapData
this.mapDataLoaded = true
}
}
</script>
getters.js
export default {
mapData: state => {
let mapData = []
state.condensed.forEach(country => {
mapData[country.alpha_2] = country.confirmed
})
return mapData
}
}
actions.js
export default {
async fetchCondensedDetails({ commit }, path) {
try {
if (path === '/') {
const res = await fetch('https://covidapi.info/api/v1/global/latest')
commit('SET_CONDENSED_DETAILS', await res.json())
}
} catch (err) {
console.log(err)
}
}
}
mutations.js
export default {
SET_CONDENSED_DETAILS: (state, data) => {
data.result.forEach((element, index) => {
const key = Object.keys(element)[0]
let details = countries.find(country => {
if (country.alpha_3 === key) return country
})
if (details) {
state.condensed.push({
...data.result[index][key],
alpha_3: key,
alpha_2: details.alpha_2,
name: details.name
})
}
})
}
}
【问题讨论】:
-
country.alpha_2 是一个数字吗?
-
@Anatoly 是的,country.alpha_2 是一个数字。可能值得注意的是,如果我在挂载函数结束时 console.log this.mapInformation 我得到了所需的数据,只有在渲染到模板时才不起作用。
标签: javascript vue.js vuejs2 vue-component vuex