gpt4 book ai didi

javascript - 如何在JS中编写api类并调用Vuex更改状态

转载 作者:行者123 更新时间:2023-11-28 03:21:03 25 4
gpt4 key购买 nike

我需要用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com