我正在尝试从外部API提取数据并在我的组件中显示数据,但是当我的API中实际有数据时,它将返回一个空数组。在我的模块中,我有以下内容:
import axios from 'axios';
const state = {
countries = []
}
const getters = {
allCountries: (state) => state.countries;
}
const actions = {
//Fecth all the countries from the API
async fetchCountries({ commit }) {
const response = await axios.get('URL');
commit('setCountries', response.data);
},
}
const mutations = {
setCountries: (state, countries) => (state.countries = countries),
}
export default {
state,
getters,
actions,
mutations,
};
Component:
<template>
<div v-for="country in allCountries" :key="country.id">
<small>{{country.name}}</small>
</div>
</template>
<script>
import { mapGetters} from 'vuex';
export default{
name: 'CompCountry',
computed: mapGetters(['allCountries'])
}
</script>
缺少您要分派的动作,为此,您应该在诸如mounted
的生命周期挂钩中运行它:
<template>
<div v-for="country in allCountries" :key="country.id">
<small>{{country.name}}</small>
</div>
</template>
<script>
import { mapGetters} from 'vuex';
export default{
name: 'CompCountry',
computed:{ ...mapGetters(['allCountries']},
mounted(){
this.$store.dispatch('fetchCountries')
}
}
</script>