我需要用 Javascript 编写一个 api 类并从 api 类更改 Vuex 状态。
这是 store.js 文件 (vuex)
api调用需要写在不同类中的action有:getCurrentWeatherData()
和getDailyWeatherData()
import Vue from "vue";
import Vuex from "vuex";
import plugins from "../../plugins/plugins";
import Axios from "axios";
Vue.use(Vuex);
const store = new Vuex.Store({
strict: true,
state: {
city: JSON.parse(window.localStorage.getItem("location") || " "),
currentWeatherData: [],
dailyWeatherData: []
},
getters: {
getIcon(state) {
let icon = state.currentWeatherData.weather.icon;
return "https://www.weatherbit.io/static/img/icons/" + icon + ".png";
}
},
mutations: {
updateCity(state, city) {
state.city = city;
},
setCurrentWeatherData(state, currentWeatherData) {
state.currentWeatherData = currentWeatherData;
},
setDailyWeatherData(state, dailyWeatherData) {
state.dailyWeatherData = dailyWeatherData;
}
},
actions: {
getCurrentWeatherData({commit}) {
let url = "https://api.weatherbit.io/v2.0/current",
key = "key=d278d8fd45ac4a779a5949bd6ee4f37e";
Axios.get(url + "?" + key + "&" + "city=" + this.state.city)
.then(res => {
commit("setCurrentWeatherData", res.data.data[0]);
})
.catch(err => {
throw err;
});
},
getDailyWeatherData({commit}) {
let url = "https://api.weatherbit.io/v2.0/forecast/daily",
key = "key=d278d8fd45ac4a779a5949bd6ee4f37e",
days = "days=" + 3;
Axios.get(url + "?" + key + "&" + days + "&" + "city=" + this.state.city)
.then(res => {
commit("setDailyWeatherData", res.data.data);
})
.catch(err => {
throw err;
});
}
},
plugins
})
export default store
感谢任何帮助,非常感谢您的帮助!
最佳答案
如何在 Vue 实例之外使用 Vuex(例如 Vue.use(Vuex)
):
取自Vuex官方指南https://vuex.vuejs.org/guide/以下应该有效。适应您的需要。
/* apiclass.js */
import Store from './store'; /* or wherever your store file is located */
class ApiClass {
constructor() {
// ...
}
storeActionDispatch() {
Store.dispatch('getCurrentWeatherData');
}
}
export default ApiClass;
/* example.js */
import ApiClass from './apiclass';
const api = new ApiClass();
api.storeActionDispatch(); // This will trigger the Vuex Action
关于javascript - 如何在JS中编写api类并调用Vuex更改状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59153164/