我是Vue的新手,我想知道如何从多个请求中获取数据,将其存储在一个对象中,然后对数据进行一些操作...(格式化日期,添加货币属性等) ..)
例如:
假设这些是我的要求:
'https://jsonplaceholder.typicode.com/posts/1'
'https://jsonplaceholder.typicode.com/posts/2'
'https://jsonplaceholder.typicode.com/posts/3'
所以我想做类似的事情:
设置状态变量以存储所有ID,以便以后在其上循环
state: {
ids:[1,2,3],
posts:[],
alteredPostsArr :[]
},
处理请求并存储所有数据
var dataStored = [];
var ids = this.state.ids
for(var i=0; i< ids.length; i++){
axios
.get('https://jsonplaceholder.typicode.com/posts/'+ids[i])
.then(function(response){
dataStored.push(response.data)
console.log(response.data);
})
}
this.state.posts = dataStored // store all results
创建一个操作数据的函数...类似
setDate :function(data){ // loop over this.state.posts
for(var i=0; i< data.length; i++){
var newDataObj = {
"userId": data[i].userId,
"id": data[i].id,
"title": data[i].title,
"body": data[i].body,
"date":new Date(),
}
this.state.alteredPostsArr.push(newDataObj )
}
}
我已经研究过vuex教程,但我不知道应该将axios请求循环放在哪里...所以我试图将其放入Actions中,就像这里一样,但是我得到了空数组... ..
export default new Vuex.Store({
state: {
posts:[],
ids:[1,2,3],
alteredPostsArr:[],
},
methods:{
setDate:function(data){
// loop over this.state.posts
for(var i=0; i< data.length; i++){
var newDataObj = {
"userId": data[i].userId,
"id": data[i].id,
"title": data[i].title,
"body": data[i].body,
"date":new Date(),
}
this.state.alteredPostsArr.push(newDataObj )
}
}
},
actions: {
loadPosts ({ commit }) {
var dataStored = [];
var ids = this.state.ids
for(var i=0; i< ids.length; i++){
axios
.get('https://jsonplaceholder.typicode.com/posts/'+ids[i])
.then(function(response){
dataStored.push(response.data)
})
}
this.state.posts = dataStored // store all results
}
},
mutations: {
SET_POSTS (state, posts) {
state.posts = posts
}
}