Nuxt - 具有多个请求的异步数据

Nuxt - asyncData with multiple requests

在我的应用程序中,我有一个卖家页面,显示该卖家列出的产品。我正在使用 asyncData 获取页面所需的所有数据(对 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 进度条显示两次(奇数)。

我已经搜索了一段时间,试图在 asyncData 中找到多个请求的示例,但没有太多内容。

也许我不应该在 asyncData 中调用多个请求?

也许是这样?

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 将等待所有承诺完成并 return 调用结果。

实际上,您可以使用 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>

here 是它的一个工作沙箱。 (不要忘记为 :id 路由参数添加一个值)

尝试使用 async await,这就是 运行 并行请求的方法:

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

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