vue.js内でaxiosを使う場合複数のAPIリクエストをしたい場合があります。その時にきれいにやる方法です。
index.vue
<template>
省略
</template>
<script>
import axios from 'axios'
function getData () {
return Promise.all([
axios.get(process.env.API_URL + '/posts'),
axios.get(process.env.API_URL + '/services'),
axios.get(process.env.API_URL + '/shops'),
]).then(([posts, services, shops]) => {
const data = {}
data.posts = posts.data
data.services = services.data
data.shops = shops.data
return Promise.resolve(data)
})
}
export default {
async asyncData () {
const data = await getData()
return {
posts: data.posts,
shops: data.shops,
services: data.services
}
}
}
</script>
<style>
省略
</style>