【问题标题】:NuxtJS asyncData from component来自组件的 NuxtJS asyncData
【发布时间】:2021-10-25 17:20:48
【问题描述】:

我尝试学习 nuxtjs,现在我在 asyncData。如果我理解正确,则在加载 asyncData 后处理从页面转换的加载。然后我有一个问题,如果我的 axios 请求不是在 asyncData 中,而是在一个组件中。我发现 AsyncData 在组件中不起作用,或者说转换不等待加载。如何在所有组件响应之前加载页面?

<template lang="pug">
  .main
    post-list(:posts="posts")
    ros-list(:posts="posts")
    gos-list(:posts="posts")
</template>

现在我有 3 个组件。在他们每个人都有 axios 请求,我怎么能告诉 nuxt 页面等待他们加载?

现在我正在使用 asyncData,但我无法将其传输到组件。

asyncData({ params }) {
    return axios.get("***").then(post => {
        return post;

【问题讨论】:

  • 你能分享完整的组件吗?
  • 它不是组件它是一个页面,在组件中只是 axios 请求
  • 这可行但相当复杂,因为它必须使用fetch 完成。你不能使用fetch()钩子并添加一些骨架吗? buefy.org/documentation/skeleton

标签: vue.js nuxt.js


【解决方案1】:

来自https://nuxtjs.org/docs/2.x/features/data-fetching

Nuxt 有两个用于异步数据加载的钩子

获取钩子(Nuxt 2.12+)。这个钩子可以放在任何组件上,并提供渲染加载状态(在客户端渲染期间)和错误的快捷方式。

asyncData 钩子。 此钩子只能放置在页面组件上。 与 fetch 不同,此钩子在客户端渲染期间不显示加载占位符:相反,此钩子会阻止路由导航,直到它被解决,显示页面错误如果失败。

我认为 Axios 文档指的是 Nuxt 的早期版本。 Fetch 挂钩已在 v 2.12 中引入

这是一篇很好的文章,解释了 fetch(有和没有 Axios)

https://nuxtjs.org/blog/understanding-how-fetch-works-in-nuxt-2-12

这是我在安装 nuxt 时的做法:


    async fetch () {
        const response = await this.$axios.$get('/api/v1/municipalities', {
            params: {
            // Url params as JSON
            name: this.mySearch
            other_param: this.otherStuff
          }
        })
        // do stuff with the response
      }

(我是 nuxt.js 的新手,但多年来第一次潜伏在 stackoverflow 上,我觉得很有用:D)

【讨论】:

    猜你喜欢
    • 2019-02-02
    • 2019-11-28
    • 2020-01-31
    • 2020-02-06
    • 2021-05-10
    • 2021-09-23
    • 2019-02-13
    • 2023-03-21
    • 2021-10-09
    相关资源
    最近更新 更多