大家好,我在vuejs和javascript代码中使用axios.all。但是,在加载页面时,看不到任何内容,并且在chrome控制台中显示为:
[nuxt]Error while initializing app ReferenceError: getAllTicketGroups is not defined.
我不确定为什么会这样。
下面是我正在使用的JavaScript代码。
<script>
import axios from 'axios';
export default {
layout: 'Account',
components:{
'accountTickets' : TicketsAccountTickets
},
data(){
return{
allTickets: [],
event_id : this.event_id,
getTickets:{
seeTickets:{
event_id : this.event_id
}
},
findTickets: {},
eventsId: [],
}
},
mounted:{
getAllTicketGroups: function(){
return axios.get('https://api.ticketpass.co/tickets',{
headers:{
"Content-Type" : "application/json",
"Accept" : "application/json"
}
})
.then(response =>{
if(response.status === 200){
for(let i = 0; i < response.data.length; i++){
console.log(response.data[i].event_id);
this.allTickets.push({
"some_id" : response.data[i].id,
"event_id" : response.data[i].event_id,
"created" : response.data[i].created,
"code" : response.data[i].code,
"user_id" : response.data[i].user_id
})
this.getTickets.seeTickets = {
"event_id" : response.data[i].event_id
}
}
}
})
},
getEventId: function(){
if(!(response.data[i].event_id in this.findTickets) && this.eventsId.indexOf(response.data[i].event_id) == -1){
return axios.get('https://api.ticketpass.co/event/' + response.data[i].event_id,{
headers:{
"Content-Type" : "application/json",
"Accept" : "application/json",
"Authorization" : this.accessToken
}
})
.then(response => {
console.log(response.data);
this.findTickets[response.data.id] = response.data;
})
console.log("Data Added");
}else{
console.log("IN Object");
}
console.log(this.findTickets);
}
}
}
axios.all([getAllTicketGroups(), getEventId()])
.then(axios.spread(function (list, got){
console.log(list);
console.log(got);
}));
</script>
如果有人可以帮助您,将不胜感激。
非常感谢。
答案 0 :(得分:2)
您的Vue结构和某些逻辑部分不正确:
mounted
部分重命名为methods
,我认为这是拼写错误。 您不能使用问题中提供的方法来调用方法,不能将初始请求放置到mounted
或created
钩子上并在this
上调用方法:
mounted() {
axios.all([this.getAllTicketGroups(), this.getEventId()])
.then(axios.spread(function (list, got){
console.log(list);
console.log(got);
}));
}
还要在response
方法的顶部引用一些getEventId
变量,由于未声明,因此始终为 undefined 。
在主请求成功完成之后,您也不会在控制台中看到任何内容,因为您没有在getAllTicketGroups
和getEventId
“ thens”中返回任何内容。因此,您应该在then
中返回您的回复,以使console.log
显示您的回复。
更新
请求链接票证,快速示例:
mounted() {
this.getAllTicketGroups().then((response) => {
let requests = [];
this.allTickets.forEach((t) => {
requests.push(this.getEventId(t.event_id));
});
return axios.all(requests);
});
}
...
getEventId: function(event_id){
if(!(event_id in this.findTickets) &&
this.eventsId.indexOf(event_id) == -1){
return axios.get('https://api.ticketpass.co/event/' + event_id,{
headers:{
"Content-Type" : "application/json",
"Accept" : "application/json",
"Authorization" : this.accessToken
}
})
.then(response => {
console.log(response.data);
this.findTickets[response.data.id] = response.data;
})
console.log("Data Added");
}else{
console.log("IN Object");
}
console.log(this.findTickets);
}