javascript - How to write an api class in JS and call Vuex for change state
问题描述
I need to write an api class in Javascript and change the Vuex state from the api class.
This is the store.js file (vuex)
Actions that need to be written in different classes for api call is: getCurrentWeatherData()
, and 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
Any help is appreciated, and thanks a lot for helping!
解决方案
如何在 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
推荐阅读
- android - 有没有办法以编程方式将文件从 Android 应用程序上传到 Google Drive?
- python - 我如何显示可视化的价值
- python - 将熊猫数据框列值从字符串转换为浮点数
- javascript - Angular 中的用户 JsonWebToken -> 方法发布
- java - 未知方言支持 REF_CURSOR 参数
- ios - 如何在 iOS 设备和 Mac OS 设备的 safari 浏览器中录制音频和视频?
- r - 将循环应用于几个数据帧
- flutter - 当我按下凸起的按钮时,如何在按钮内的文本下附加滑块?
- postgresql - PostgreSQL 输入批量数据时跳过关系错误
- php - 无法使用 ImageMagick 和 GhostScript 将 PDF 转换为 JPG