Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vue.js VUEX Getter返回得太快_Vue.js - Fatal编程技术网

Vue.js VUEX Getter返回得太快

Vue.js VUEX Getter返回得太快,vue.js,Vue.js,我对getter有问题。首先,我调用一个动作getWeather,它是async: export const actions = { async getWeather ({commit, state}) { try { const locationResponse = await VueGeolocation.getLocation({ enableHighAccuracy: true }); const url =

我对getter有问题。首先,我调用一个动作
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>

如何在
index.vue
文件中获取天气数据而不为null?

创建的
中看到
null
的原因是,在
创建之前启动的异步操作尚未完成

如果您确实需要在创建中完成操作结果,则需要:

async created(){
等待此消息。$store.dispatch('getWeather');
console.log(this.$store.getters.getWeatherInfo)//现在数据已存储
}

如果您不需要在创建的
中准备好数据,那么最好删除
等待
并使用
v-If
-“仅当我的getter不为null时渲染它”…它最终不会为null(“将来某个时候”)Vue将重新呈现您的组件…

您真的需要
getWeatherInfo
中创建值吗
还是只是一个“实验”?没有必要,它也不适用于计算的getter
wait commit('SET_WEATHER',data')
-remove
await
,commit是同步的(不返回Promis)并且不能等待…它仍然是
null
,在控制台中我可以看到,首先我得到getters值
null
,然后是
控制台。log(
数据:${DATA}
当然会记录我,因为在
created
中,您的异步调用(来自操作)尚未完成
export const mutations = {
    SET_WEATHER (state, payload) {
        state.weather = payload;
    }
}