【发布时间】: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] -
我刚试了一下,还是不行
-
感谢您的链接,我终于明白如何在我的案例中应用它了。