IT이야기

JS에서 api 클래스를 작성하고 Vuex에 전화하여 상태를 변경하는 방법

cyworld 2022. 5. 10. 22:26
반응형

JS에서 api 클래스를 작성하고 Vuex에 전화하여 상태를 변경하는 방법

Javascript에서 api 클래스를 쓰고 api 클래스에서 Vuex 상태를 변경해야 해.api 호출을 위해 다른 클래스로 작성해야 하는 store.js 파일(vuex) 작업은 다음과 같다.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 

참조URL: https://stackoverflow.com/questions/59153164/how-to-write-an-api-class-in-js-and-call-vuex-for-change-state

반응형