LoginSignup
33
29

More than 5 years have passed since last update.

NuxtのasyncDataで複数のHTTPリクエストを扱う

Posted at

asyncDataに限らないんだけど await Promise.all() 使うとキレイに書けるよねって話。
TypeScript x ES6 な感じ。

prefetch的な処理をキレイにかけるNuxtは最高だなと思います:relaxed:

FooBar.vue
<script lang="ts">
import Vue from "vue";
import Component from "nuxt-class-component";

import Foo from "~/Foo";
import Bar from "~/Bar";

@Component({
  async asyncData({ app, params }) {
    const id = _.get(params, "id");
    // 2つのHTTPのレスポンスを受けてからページがレンダリングされる
    const [foo, bar] = await Promise.all([
      app.$axios.get(`/foo/${id}`),
      app.$axios.get(`/bar/foo/${id}`),
    ]);
    return { foo, bar };
  },
})
export default class extends Vue {
  foo: Foo;
  bar: Bar;
};
</script>
33
29
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
33
29