VUEX吸气剂返回得太快

时间:2019-12-16 19:37:40

标签: vue.js

我对吸气剂有疑问。首先,我叫一个getWeather的动作async

export const actions = {
        async getWeather ({commit, state}) {
        try {
            const locationResponse = await VueGeolocation.getLocation({ enableHighAccuracy: true });
            const url = `https://api.openweathermap.org/data/2.5/weather?lat=${locationResponse.lat}&lon=${locationResponse.lng}&units=metric&appid=${process.env.apikey}`;

            const response = await fetch(url);
            const data = await response.json();
            await commit('SET_WEATHER', data);
            console.log(`DATA: ${data}`) // returns me the weather data

        } catch (error) {
            return console.log(error);
        }
    }
}

然后在我的index.vue文件中输入:

<script>
import { mapActions, mapGetters } from 'vuex';

export default {
  beforeCreate() {
    this.$store.dispatch('getWeather');
  },
  created() {
    console.log(this.$store.getters.getWeatherInfo) // returns null
  },
  computed: {
    ...mapGetters(['getWeatherInfo'])
  }
}
</script>

即使我null,也从状态返回mutate的值。 created() { console.log(this.$store.getters.getWeatherInfo) // returns null

Vuex突变:

export const mutations = {
    SET_WEATHER (state, payload) {
        state.weather = payload;
    }
}

如何获取index.vue文件中的天气数据然后不为null?

1 个答案:

答案 0 :(得分:0)

null中看到created的原因是,在beforeCreate中启动的异步操作尚未完成。

如果确实需要完成操作的结果,则需要执行以下操作:

async created() {
  await this.$store.dispatch('getWeather');
  console.log(this.$store.getters.getWeatherInfo) // now the data is in store
}

如果您不需要在created中准备数据,则最好删除await并使用v-if编写组件模板-“仅当我的getter不为null时才呈现此模板“ ...最终将不会为空(“将来的某个时候”),Vue将重新渲染您的组件...