Programing

Nuxt - 여러 요청이 있는 비동기 데이터

c10106 2022. 4. 26. 20:43
반응형

Nuxt - 여러 요청이 있는 비동기 데이터

내 애플리케이션에는 그 판매자가 나열한 제품을 표시하는 판매자 페이지가 있다.페이지에 필요한 모든 데이터를 가져오기 위해 비동기 데이터를 사용하는 경우(SEO에 더 적합)

asyncData ({params, app, error }) {

    return app.$axios.$get(`/seller/${params.username}`).then(async sellerRes => {

        let [categoriesRes, reviewsRes, productsRes] = await Promise.all([
            app.$axios.$get(`/categories`),
            app.$axios.$get(`/seller/${params.username}/reviews`),
            app.$axios.$get(`/seller/${params.username}/products`)
        ])

        return {
            seller: sellerRes.data,
            metaTitle: sellerRes.data.name,
            categories: categoriesRes.data,
            reviewsSummary: reviewsRes.summary,
            products: productsRes.data,
        }

    }).catch(e => {
        error({ statusCode: 404, message: 'Seller not found' })
    });
},

비록 이 방법이 그 일을 의도한 것은 맞지만, 나는 내가 이것을 잘못하고 있다고 생각하지 않을 수 없다.

페이지로 이동할 때 nuxt 진행 표시줄이 두 번(홀수) 표시됨.

비동기 데이터에서 여러 요청의 예를 찾기 위해 지금 한참을 검색해 보았지만, 별로 많지 않다.

비동기 데이터로 여러 요청을 호출하면 안 되는 거 아닐까?

비동기 대기 모드를 사용해 보십시오. 이렇게 하면 두 요청을 동시에 실행할 수 있습니다.

async asyncData ({ $axios }) {
  const [categoriesRes, articlesRes] = await Promise.all([ 
    $axios.get('/fetch/categories'),
    $axios.get('/fetch/articles'),
  ])

  return {
    categories: categoriesRes.data,
    articles: articlesRes.data,
  }
},

사실, 당신은 할 수 있다, 당신은 그것을 사용 할 수 있다.async await더 깨끗해 보이는군

<template>
  <div class="container">
    <h1>Request 1:</h1>
    <h1>{{ post.title }}</h1>
    <pre>{{ post.body }}</pre>
    <br />
    <h1>Request 2:</h1>
    <h1>{{ todos.title }}</h1>
    <pre>{{ todos.completed }}</pre>
  </div>
</template>

<script>
import axios from "axios";

export default {
  async asyncData({ params }) {
    // We can use async/await ES6 feature
    const posts = await axios.get(
      `https://jsonplaceholder.typicode.com/posts/${params.id}`
    );
    const todos = await axios.get(
      `https://jsonplaceholder.typicode.com/todos/${params.id}`
    );
    return { post: posts.data, todos: todos.data };
  },
  head() {
    return {
      title: this.post.title
    };
  }
};
</script>

여기 그것의 작업 샌드박스가 있다. (다음의 값을 추가하는 것을 잊지 말라.:id경로 매개변수)

그럴까?

asyncData ({params, app, error }) {

    return app.$axios.$get(`/seller/${params.username}`).then(sellerRes => {
        return Promise.all([
            app.$axios.$get(`/categories`),
            app.$axios.$get(`/seller/${params.username}/reviews`),
            app.$axios.$get(`/seller/${params.username}/products`)
        ]).then((categoriesRes, reviewsRes, productsRes) => {
            return {
                seller: sellerRes.data,
                metaTitle: sellerRes.data.name,
                categories: categoriesRes.data,
                reviewsSummary: reviewsRes.summary,
                products: productsRes.data,
            }
        })
    }).catch(e => {
        error({ statusCode: 404, message: 'Seller not found' })
    });

},

이것은 약속의 사슬이다.첫 번째 약속은 판매자에 대한 정보를 얻기 위해 노력하는데, 요청이 성공하면 나머지 정보를 기다리는 새로운 요청이 만들어진다.

방법asyncData모든 약속이 완료되기를 기다렸다가 통화 결과를 반환할 것이다.

참조URL: https://stackoverflow.com/questions/54120496/nuxt-asyncdata-with-multiple-requests

반응형