代码之家  ›  专栏  ›  技术社区  ›  Ulukbek Abylbekov

Vuex,Axios变量未定义

  •  0
  • Ulukbek Abylbekov  · 技术社区  · 6 年前
    import Vue from "vue";
    import Vuex from "vuex";
    import axios from "axios";
    import api from "./api_key";
    
    Vue.use(Vuex);
    
    export default new Vuex.Store({
      state: {
        data: "",
        location: "New York"
      },
      mutations: {
        GET_DATA(state, data) {
          state.data = data;
        }
      },
      actions: {
        getData({ commit }, state) {
          axios
           .get(
              `https://api.openweathermap.org/data/2.5/forecast/daily?q=${
                state.location
              }&appid=${api}&units=metric&cnt=5`
            )
            .then(data => {
              commit("GET_DATA", data);
            })
            .catch(function(error) {
              console.log(error);
            });
        }
      },
      getters: {
        data(state) {
          return state.data;
        }
      }
    });
    

    我正在开发Vue web应用程序。对于状态管理,我决定使用vuex。我的“location”和“api”变量在我的Axios请求地址中未定义。

    1 回复  |  直到 6 年前
        1
  •  1
  •   tkint    6 年前

    若要访问操作中的当前状态,您将 state 申报 getData getData({ commit, state }) .

    但是,我不明白为什么 api data 休养,更像是这样:

    .then((response) => {
         if (response.data) {
             commit("GET_DATA", response.data);
         }
    }
    

    编辑: 你的 api_key.js

    export default "my_api_key";