【发布时间】:2021-04-14 16:46:29
【问题描述】:
下面的方法调用一个天气 API,由于它需要在组件加载之前获取 API 数据,所以它被放置在一个 created 生命周期钩子中。
getWeather() {
const lat = this.$store.getters.getLatitude;
const long = this.$store.getters.getLatitude;
console.log('lat is ' + lat);
let url =
'http://api.openweathermap.org/data/2.5/weather?lat=' +
lat +
'&lon=' +
long +
'&units=metric&APPID=' +
process.env.VUE_APP_OPEN_WEATHER_API_KEY;
axios
.get(url)
.then((response) => {
this.currentTemp = response.data.main.temp + '°C';
this.minTemp = response.data.main.temp_min + '°C';
this.maxTemp = response.data.main.temp_max + '°C';
this.pressure = response.data.main.pressure + 'hPa';
this.humidity = response.data.main.humidity + '%';
this.wind = response.data.wind.speed + 'm/s';
})
.catch((error) => {
console.log(error);
});
},
},
created() {
this.getWeather();
},
Vuex 商店
import Vue from 'vue';
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
latitude: '',
longitude: '',
},
mutations: {
SET_LATITUDE(state, payload) {
state.latitude = payload
},
SET_LONGITUDE(state, payload) {
state.longitude = payload
}
},
actions: {
GET_DATA({ commit }) {
var self = this
.
.
.
// LOGIC TO GET USER DATA ( LAT AND LONG FROM DATABASE )
.
.
.
self.ddb_data = [...data.Items];
const latitude = self.ddb_data[0].user_meta_data.coordinates.latitude
const longitude = self.ddb_data[0].user_meta_data.coordinates.longitude
commit('SET_LATITUDE', latitude)
commit('SET_LONGITUDE', longitude)
}
});
}
});
});
}
} catch (e) {
console.log(e);
return;
}
},
},
},
getters: {
getLatitude(state) {
return state.latitude;
},
getLongitude(state) {
return state.longitude;
},
},
});
export default store;
问题在于从 vuex getter (即$store.getters.getLatitude 和 $store.getters.getLongitude)获取 lat 和 long。在方法内部使用时,getter 似乎没有返回数据(页面重新加载后)。当在计算属性中使用时,getter 似乎可以工作(无论页面重新加载如何)。
如何在方法中访问 getter 的数据?
【问题讨论】:
-
你能更详细地定义“不工作”吗?
-
它不返回数据。例如,在计算属性中使用 getter 时,返回预期值(例如 240.00)。但是当在方法内部使用时,它不会返回这个值(奇怪的是在重新加载页面时)
-
关于你的 vuex 初始化/水化的更多细节可能对人们也有用。作为一个在黑暗中的镜头,您是否尝试过在 nextTick 上调用 getWeather?
-
刚刚添加了 vuex 存储文件。是的,尝试了nextTick无济于事。
-
你在哪里使用 GET_DATA()?