首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从数据到asyncData

从数据到asyncData
EN

Stack Overflow用户
提问于 2019-12-10 05:34:04
回答 1查看 639关注 0票数 0

我在Nuxt和服务器端渲染我的产品时遇到了一些问题。因此,我正在尝试将我的数据方法转换为asyncData。然而,事情并没有按计划进行。我不确定我的问题是什么。

这段代码可以工作,但没有asyncData。

代码语言:javascript
复制
export default {
  components: {
    CldImage,
    CldTransformation,
    CollectionHeader,
    Loading,
    Footer
  },
  head() {
    return {
      title: this.title,
      meta: [
        { hid: 'description', name: 'description', content: 'lorem ipsum' }
      ]
    }
  },
  data: () => ({
    cloudinaryCloudName: process.env.cloudinaryCloudName,
    popularProducts: [],
    loadingPopularProducts: false,
    title: 'website.com'
  }),
  mounted() {
    this.loadingPopularProducts = true
    axios.get('/api/v1/products?popular=true&limit=6').then((response) => {
      this.popularProducts = response.data.results
      this.loadingPopularProducts = false
    })
  }
}

这是我在asyncData的go,但我收到了catch "Products not found“。

代码语言:javascript
复制
export default {
  components: {
    CldImage,
    CldTransformation,
    CollectionHeader,
    Loading,
    Footer
  },
  head() {
    return {
      title: this.title,
      meta: [
        { hid: 'description', name: 'description', content: 'lorem ipsum' }
      ]
    }
  },
  data: () => ({
    cloudinaryCloudName: process.env.cloudinaryCloudName,
    loadingPopularProducts: false,
    title: 'website.com'
  }),
  asyncData({ params, error }) {
    return axios.get('/api/v1/products?popular=true&limit=6')
      .then(response => {
        const popularProducts = response.data.results
        return { popularProducts }
      })
      .catch((e) => {
        error({ statusCode: 404, message: 'Products not found' })
      })
  }
}

如果没有捕获,我会得到这个错误

代码语言:javascript
复制
(node:14916) UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1054:14)
(node:14916) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 26)
EN

回答 1

Stack Overflow用户

发布于 2020-01-16 17:07:22

感谢您的回答。我让一个朋友看了一下,这就是对我有效的结果。

代码语言:javascript
复制
  async asyncData(context) {
    const url = '/api/v1/products?popular=true&limit=8'
    const data = await context.app.getAsyncData(url)
    return { popularProducts: data.results ? data.results : [] }
  }

只是想把答案贴出来。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59256990

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档