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

标签 javascript api class vue.js vuex

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

相关文章:

ruby-on-rails - 使用 Devise、Doorkeeper 和 OAuth2 token 的 API 和应用程序身份验证

javascript - 在 TypeScript 中克隆对象数组

c# - 如何使用 MAC 地址获取 GPS 坐标?

api - 如何使用 AJAX 在 GitHub web api 的存储库上创建 webhook?

ruby-on-rails - Ruby on Rails - 从父类调用每个子类的方法

javascript - 为什么这个 javascript 类返回 undefined

Java栈的继承

javascript - 如何在 Chrome 扩展中使用 window.print() ?

javascript - 获取包含 mongoose 模型数据的列表的函数

输入范围 slider 的 Javascript 代码在 Internet Explorer 11 中不起作用