【问题标题】:Vuex, Axios variable is undefinedVuex,Axios变量未定义
【发布时间】:2018-08-18 08:13:40
【问题描述】:
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。我的“位置”和“api”变量在我的 Axios 请求地址中未定义。

【问题讨论】:

    标签: vue.js axios vuex


    【解决方案1】:

    要访问您在操作中的当前状态,您在 getData 中放错了 state 声明。应该是这样的:getData({ commit, state })

    但是,我不明白为什么 api 是未定义的。除此之外,注意data的疗养,更像是这样的:

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

    编辑: 您的 api_key.js 文件应该包含类似这样的内容,以便使用您正在使用的导入:

    export default "my_api_key";
    

    【讨论】:

    • 不是 Axios。 api变量
    • 如何在 ./api_key 中声明 api 变量?
    • 我忘记了大括号。固定的。非常感谢
    • 好的,太好了!祝你好运
    猜你喜欢
    • 2019-03-31
    • 2020-07-13
    • 2018-05-16
    • 1970-01-01
    • 2018-05-12
    • 2018-11-23
    • 2018-08-17
    • 2020-01-17
    • 2018-11-03
    相关资源
    最近更新 更多