【问题标题】:Going from data to asyncData从数据到 asyncData
【发布时间】:2020-04-03 00:50:57
【问题描述】:

我在 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)

【问题讨论】:

  • 使用 Postman,通过那里发出请求。如果是同样的问题,那么问题出在 webpack dev 中间件使用的代理上。
  • 如何使用异步函数返回值?也许你对你的回报给你的回报感到困惑,但asynData() 的回报值并不是你承诺的结果。这是整个功能。
  • @MichalLevý 啊,我明白了。但是您是否正确使用了合并? then 回调中的返回不应该是 { popularProducts : response.data.results } 并且在您的模板中是这样的:<template> <h1>{{ popularProducts }}</h1> </template>
  • 你使用的是 Nuxt 的Axios Module 吗?从代码看来你不是。你能分享你的 Axios 设置吗?

标签: javascript vue.js nuxt.js server-side-rendering


【解决方案1】:

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

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

只是想发布答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-11
    • 2018-12-15
    • 2020-12-07
    • 2019-02-13
    • 2020-09-12
    • 1970-01-01
    • 2019-03-21
    • 2021-03-07
    相关资源
    最近更新 更多