我正在使用 Vue 和 useFetch。我对这些工具还很陌生。我正在使用组合 API 和 SFC。
我正在使用此代码获取数据:
const products = useFetch(`${URLS.BASE}fetchProducts?productCategoryId=${productCategoryId}`).get().json<any>();
然后在我的模板部分,我发现自己这样做是为了测试我的请求是否返回数据:
<AppPageTitle v-if="category.data?.value?.category"
:title="$t('category.title', { categoryName: category.data.value.category.categoryName })" />
data?.value?
的这个v-if
部分让我觉得我缺少一种更简单的方法来确保我在使用useFetch
时有数据。我读过有关 isFetching
和 isFinisehd
的内容,但我认为它们无法帮助简化这一点。
对于多个请求,以及仅在请求成功时才呈现的多个 HTML 元素,看起来有点麻烦/不理想。
我可以在这里使用更简洁的语法吗?
useFetch
附带请求失败或成功时发出的事件,记录如下:https://vueuse.org/core/useFetch/#events.
考虑到这一点,如果您不想检查响应是否包含预期数据,请使用
onFetchResponse
创建成功条件,并使用 onFetchError
创建错误条件。
const { onFetchResponse, onFetchError } = useFetch(url)
onFetchResponse((response) => {
console.log(response.status)
// Get response here, and extract what you want from it.
})
onFetchError((error) => {
console.error(error.message)
})
总的来说,我认为除了从收到的数据中解构您的价值观之外,您不能过度简化您的回答,例如:
const { category } = products
const { categoryName } = category?.data?.value?.category
<template v-if="categoryName">
<AppPageTitle :title="$t('category.title', { categoryName })" />
</template>