Vuex:吸气剂未从外部API提取数据

问题描述 投票:0回答:1

我正在尝试从外部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>
javascript vue.js vuex
1个回答
0
投票

缺少您要分派的动作,为此,您应该在诸如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>
© www.soinside.com 2019 - 2024. All rights reserved.