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