首页 > 解决方案 > 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!

标签: javascriptapiclassvue.jsvuex

解决方案


如何在 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 

推荐阅读