Vue.js Nuxt-在动态路由中访问异步数据

Vue.js Nuxt-在动态路由中访问异步数据,vue.js,nuxt.js,prismic.io,Vue.js,Nuxt.js,Prismic.io,我在处理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.s

我在处理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。

这里的问题是,不能在异步函数中使用“this”。实现所需功能的方法是使用nuxt提供的“params”上下文,这将允许您将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文件夹,只需将新闻文件夹中的index.vue重命名为_uid.vue,即可: 新闻/ _uid.vue

你可以在这里看到我们在Prismic的完整博客:
这里的问题是不能在异步函数中使用“this”。实现所需功能的方法是使用nuxt提供的“params”上下文,这将允许您将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文件夹,只需将新闻文件夹中的index.vue重命名为_uid.vue,即可: 新闻/ _uid.vue

你可以在这里看到我们在Prismic的完整博客: