axios.all()
、axios.spread()
两个辅助函数用于处理同时发送多个请求,可以实现在多个请求都完成后再执行一些逻辑。注意:该方法是axios
的静态方法,不是axios
实例的方法!
实例演示
<template>
<div>
<h1>Username: {{ userInfo.username }}</h1>
<h1>Title: {{ memo.title }}</h1>
<br>
<br>
<button @click="handleConcurrent">并发</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
data () {
return {
userInfo: {
username: 'lanyulei'
},
memo: {
title: 'lanyulei-title'
}
}
},
mounted () {
this.handleConcurrent()
},
methods: {
handleConcurrent () {
var _this = this
axios.all([
axios.get('/user.json'),
axios.get('/memo.json')
]).then(axios.spread((userRes, memoRes) => {
_this.userInfo = userRes.data
_this.memo = memoRes.data
})).catch(err => {
console.log(err)
})
}
}
}
</script>