我刚使用vue做一个网站,其中有“热点文章”和“推荐文章”列表,于是我把它们写成一个组件,其中有两个同时运行的axios请求,分别获得热点列表和推荐列表数据。但我发现这两个数据总是混淆或相互覆盖。于是用了axios.all方法。
methods: {
// 热点
getHotlist: function(columnId, number) {
return this.$axios({
method: 'post',
url: 'http://localhost:8090/articles/hotlist',
data: {
columnId: columnId,
number: number
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded;'
}
})
},
// 推荐
getRecommendlist: function(number) {
return this.$axios({
method: 'post',
url: 'http://localhost:8090/articles/recommendlist',
data: {
number: number
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded;'
}
})
},
getData: function() {
let that = this
this.$axios.all([that.getHotlist(that.columnId, 4), that.getRecommendlist(4)])
.then(
that.$axios.spread(function(hotdata, recdata) {
console.log('所有请求完成')
console.log('请求1结果', hotdata)
console.log('请求2结果', recdata)
} else {
that.$message.error(recdata.data.status.msg)
}
}))
}
},mounted: function() {
this.getData()
}
我按网上的写法写的。但是有一定概率spread中的参数hotdata和recdata是一样的。应该是覆盖了,混乱了。hotdata取成返回的recdata的数据了,亦或相反。
我试着把两个请求分开写入两个独立的组件,但只要在同一页面出现,同时运行,就有概率会乱。组件间的axios请求也会乱。
以前用jquery时也有多个ajax同时请求的情况,但也没乱过呀。
以前就没听说过不同的请求间回调获得的数据还会乱……这种情况常见不?如何解决呢?
问题是axios.all可能返回的两个数据是同一个,不是因为axios.all本身问题,而是因为请求是异步的,而两个请求可能同时完成导致回调中的两个数据是同一个。解决方法是将请求设置为同步请求,或者通过使用setTimeout等方法控制请求的完成顺序。
可能是多个请求的请求完成的顺序不一致,所以数据在spread的参数顺序中会被覆盖,造成相同的数据。你可以尝试在console.log中打印每个请求的时间戳,以查看请求完成的顺序。解决方法是使用async/await代替axios.all,以保证每个请求完成后才继续执行下一个请求。例如:
async getData() {
try {
const [hotdata, recdata] = await Promise.all([this.getHotlist(this.columnId, 4), this.getRecommendlist(4)])
console.log('请求1结果', hotdata)
console.log('请求2结果', recdata)
} catch (error) {
this.$message.error(error.response.data.status.msg)
}
}
netWork 里面看接口返回参数是不一致的吗?
不知道你这个问题是否已经解决, 如果还没有解决的话: