简体   繁体   English

如何将 useAsync + 错误迁移到 nuxt-bridge(useAsyncData 不可用)

[英]How to migrate useAsync + error to nuxt-bridge (useAsyncData is not available)

I'm trying to migrate a nuxt 2 app to nuxt-bridge.我正在尝试将 nuxt 2 应用程序迁移到 nuxt-bridge。

In this app I frequently fetch data from an API based on URL parameters of the frontend.在这个应用程序中,我经常根据前端的 URL 参数从 API 获取数据。 Like this (simplified):像这样(简化):

  setup() {
    const { $axios, error, params } = useContext()

    const foo = useAsync(async () => {
      try {
        return await $axios.$get(`...${params.value.foo}`)
      } catch () {
        error({ statusCode: 404, message: 'Not found' })
      }
    })

    return { foo }
  }

This "tiny" limitation that useAsyncData is not available hits me pretty hard.这个useAsyncData不可用的“微小”限制对我造成了很大的打击。

If I get it right, I would have to use useLazyAsyncData instead and handling pending and error states in my template.如果我做对了,我将不得不改用useLazyAsyncData并在我的模板中处理挂起和错误状态。 Which means I have to wrap all my current templates with something like:这意味着我必须用以下内容包装我当前的所有模板:

<div v-if="pending">
... show something while loading ...
</div>
<div v-else-if="error">
... show error page - not even sure how to do this as my error page is based on a different layout ...
</div>
<div v-else>
... current template ...
</div>

That means:这意味着:

  • I cannot properly respond with a HTTP 404 code.我无法正确响应 HTTP 404 代码。
  • When I finally move to nuxt3 I would have to revert all that again.当我最终搬到 nuxt3 时,我将不得不再次恢复所有这些。

Is that correct?那是对的吗? Is there a better way to do it?有更好的方法吗?

Yes, the migration path you proposed with useLazyAsyncData is correct.是的,您使用useLazyAsyncData提出的迁移路径是正确的。 Another option is not using the Composition API yet and sticking to Nuxt 2's asyncData .另一种选择是不使用组合 API 并坚持 Nuxt 2 的asyncData

I also got this problem.我也遇到了这个问题。 I solved this by creating <HttpError /> component like below我通过创建<HttpError />组件解决了这个问题,如下所示

<script lang="ts" setup>
import { createError } from 'h3';

const { statusCode = 404, statusMessage = 'Not Found' } = defineProps<{
  statusCode: number;
  statusMessage: string;
}>();
throw createError({ statusCode, statusMessage });
</script>

and used it并使用它

<script lang="ts" setup>
import HttpError from '~/components/HttpError';
const { data, error } = useLazyAsyncData(...);
</script>
<template>
  <div>
    <HttpError v-if="error" :status-code="404" />
    <div v-else>
      ...
    </div>
  </div>
</template>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM