【问题标题】:Axios API Call failing to save full array response into variableAxios API 调用未能将完整的数组响应保存到变量中
【发布时间】:2021-10-15 13:25:51
【问题描述】:

我正在使用 Axios 从 API 获取数据并将这些数据保存到一个空变量中。但是,我无法将整个 API 调用保存到该变量。

export default createStore({
  state: {
    apiUrl: "http://localhost:8090/", 
    monthlyData: [],
    
  },
  mutations: {
    setMonthlyData(state, newValue){
      state.monthlyData = newValue
    },
  },
actions: {
  getData({ commit, dispatch, state }) {
  console.log("Fetching  monthly data from the backend...");
      axios.get(state.apiUrl + "/monthly/4")
        .then(response => {
          commit('setMonthlyData', response.data)
            console.log(response.status);
            console.log(response.data);
            console.log(response.data.length);
        })
        .catch(error => {
          console.error(error);
        })
    
      }

这是 API 调用的结果,我想保存在一个变量中

[{"date":"2021-01-16","month":"Jan","name":"User Negative Hour 6","projects":["63213","53213","83213","73213","213213","53212"],"quarter":"Q1","year":"2021"},{"date":"2021-02-16","month":"Feb","name":"User Negative Hour 6","projects":["213213","63213","53212","73213","53213","83213"],"quarter":"Q1","year":"2021"},{"date":"2021-03-16","month":"Mar","name":"User Negative Hour 6","projects":["53212","63213","213213","83213","73213","53213"],"quarter":"Q1","year":"2021"}]

但该值并未存储在monthlyData 变量中。但是,如果我这样做了

commit('setMonthlyData', response.data[0])

这会起作用,我将从 API 获取数组的第一个元素。但这不是我想要的(所有数组而不是给定元素)。

{"date":"2021-01-16","month":"Jan","name":"User Negative Hour 6","projects":["63213","53213","83213","73213","213213","53212"],"quarter":"Q1","year":"2021"}

response.status 是 200,response.data.length 应该是 3。

我正在努力找出我做错了什么。有什么建议吗?

【问题讨论】:

  • 您是否尝试传播数据state.monthlyData = [...newValue]
  • 我刚试了一下,还是不行
  • 感谢您的链接,我终于明白如何在我的案例中应用它了。

标签: vue.js axios vuex


【解决方案1】:

请查看此答案:Committing array to Vuex store mutation

也许你可以试试

  mutations: {
    setMonthlyData(state, newValue){
      Vue.set(state, 'monthlyData', newValue)
    },
  },

【讨论】:

    【解决方案2】:

    在 store/index.js 文件中,我使用 .items 更新了 setMonthlyData 函数

    setMonthlyData(state, newValue){
            state.monthlyData.items = newValue
    
    axios.get(state.apiUrl + "monthly/4")
            .then(response => {
              commit('setMonthlyData', response.data)
    

    在一个视图中,我将其称为如下:

    this.$store.getters.monthlyBillability.items
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 2021-06-23
      • 1970-01-01
      • 2013-04-26
      • 2014-11-09
      • 1970-01-01
      • 2022-06-27
      相关资源
      最近更新 更多