1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Vue Axiosで複数のAPIを同時に叩いて取得する方法

Last updated at Posted at 2022-07-18

殴り書きなので不正確な内容はご了承を。

Vue AxiosなんかでAPIからデータを取得する関数なんかを作って...

functions.js
getUserList () {
  return this.axios.get('https://hogehoge.net/getUserList')
  .then(resnponse => {
    return response.data
  })
  .catch(error => {
    console.log(error)
  })
}

getScore () {
  return this.axios.get('https://hogehoge.net/getScore')
  .then(response => {
    return response.data
  })
  .catch((error => {
    console.log(error)
  })
}

一つずつ取得するのであれば、

single.vue
()
import functions from './functions'

const single = {
  data () {
    return {
      myUserList: [],
      myScore: []
    }
  },
  async created () {
    this.myUserList = await this.getUserList()
  },
  watch : {
    async myUserList () {
      this.myScore = await this.getScore()
    }
  },
  methods: {
    ...functions
  }
}

export default single

とすればいいが、同時に取得したいのであれば、

multi.vue
()
import functions from './functions'

const multi = {
  data () {
    return {
      myUserList: [],
      myScore: []
    }
  },
  created () {
    Promise.all([
      this.getUserList(),
      this.getScore()
    ])
    .then(response => {
      this.myUserList = response[0]
      this.myScore = response[1]
    })
    .catch(error => {
      console.log(error)
    })
  },
  methods: {
    ...functions
  }
}

export default multi

と、Promise.all()を使えばOK。
async / await に慣れていると、この方法にたどり着けなかった。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?