从数据到异步数据

问题描述 投票:0回答:1

我在Nuxt和产品的服务器端渲染方面遇到一些问题。所以我试图将我的数据方法转换为asyncData。但是,事情并没有按计划进行。我不确定我的问题是什么。

此代码有效,但没有asyncData。

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的地方,但是我收到了“找不到产品”的提示。

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' })
      })
  }
}

没有抓住我的错误

(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)
javascript vue.js nuxt.js server-side-rendering
1个回答
0
投票

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

  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 : [] }
  }

只想发布答案。

© www.soinside.com 2019 - 2024. All rights reserved.