1

我在处理 Nuxt 动态路由中的异步数据时遇到问题。

文件夹结构示例,

在此处输入图像描述

我的异步数据

async asyncData({context, error, req}) {
  try {
    const api = await Prismic.getApi(PrismicConfig.apiEndpoint, {req})

    let document = []
      const result = await api.getByUID('news', this.$route.params.slug)
      document = result.results

    return {
      document,
      documentId: result.id,
    }
  } catch (e) {
      error({ statusCode: 404, message: 'Page not found' })
    }
}, 

所以我总是以找不到 404 页面结束。我尝试了其他在正常“非动态路由”上正常工作的异步数据示例,它也返回 404。

我假设这是与 Nuxt 与组件的异步数据相关的问题,这是 Nuxt 将在 3.0 版中处理的问题?

但在那之前,如果你能帮我解决这个问题,我将不胜感激,我需要以某种方式完成这项工作。

我使用 Prismic 作为无头 API cms。

4

1 回答 1

4

这里的问题是您不能在异步函数中使用“this”。完成您需要的方法是使用 nuxt https://nuxtjs.org/api/context提供的“参数”上下文,这将允许您将 uid 传递给查询。您可以在下面看到如何执行此操作。

async asyncData({ params, error, req }) {
  try{
    // Query to get API object
    const api = await Prismic.getApi(PrismicConfig.apiEndpoint, {req})

    // Query to get content by 'news' type and whatever the uid for the document is
    const result = await api.getByUID("news", params.uid)

    // Returns data to be used in template
    return {
      document: result.data,
      documentId: result.id,
    }
  } catch (e) {
    // Returns error page
    error({ statusCode: 404, message: 'Page not found' })
  }
},

此外,对于您的文件结构,您不需要 _slug 文件夹,您只需将 news 文件夹中的 index.vue 重命名为 _uid.vue 并具有:news/ _uid.vue

您可以在此处查看我们在 Prismic 上制作的完整博客: https ://user-guides.prismic.io/en/articles/2802125-create-a-sample-blog-with-prismic-and-nuxt

于 2019-03-26T13:02:52.957 回答