You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Vue和useFetch时,检查请求数据是否可用的最简洁方式是什么?

简化useFetch数据访问的几种实用方法

1. 用计算属性包装深层数据

直接创建计算属性提取你要的最终字段,模板里不用再写冗长的链式调用:

import { computed } from 'vue';

const productsFetch = useFetch(`${URLS.BASE}fetchProducts?productCategoryId=${productCategoryId}`).get().json<any>();
const categoryData = computed(() => productsFetch.data?.value?.category);

模板里直接这么写:

<template>
  <div v-if="categoryData">
    <!-- 渲染内容 -->
  </div>
</template>

多请求场景下,每个请求对应一个计算属性,逻辑清晰,模板也干净。

2. 异步等待请求完成(适合无需实时加载状态的场景)

在<script setup>里用async配合await直接拿到最终数据,省去层层访问:

<script setup>
const productsFetch = useFetch(`${URLS.BASE}fetchProducts?productCategoryId=${productCategoryId}`).get().json<any>();
const { data: productsData } = await productsFetch;
const category = productsData?.category;
</script>

模板里直接判断v-if="category"就行。如果需要加载状态,还是可以配合isFetching做loading提示。

3. 自定义封装hook统一简化逻辑

如果多个请求都要处理这种深层数据访问,自己封装个hook复用:

// hooks/useCustomFetch.ts
import { useFetch } from '@vueuse/core';
import { computed } from 'vue';

export function useCustomFetch<T>(url: string) {
  const fetchResult = useFetch(url).get().json<T>();
  return {
    // 直接返回data.value的计算属性
    data: computed(() => fetchResult.data?.value),
    // 保留原有的状态字段
    isFetching: fetchResult.isFetching,
    isFinished: fetchResult.isFinished,
    error: fetchResult.error
  };
}

用的时候就简单多了:

const { data: productsData } = useCustomFetch<any>(`${URLS.BASE}fetchProducts?productCategoryId=${productCategoryId}`);
const category = computed(() => productsData?.category);

模板里依旧用v-if="category",多请求场景下重复调用这个hook就行,不用每次都写data?.value。

4. 模板里用空值合并运算符优化判断

如果不想额外写计算属性,也可以在模板里用??简化判断逻辑:

<template>
  <div v-if="products.data?.value?.category ?? false">
    <!-- 渲染内容 -->
  </div>
</template>

不过这种只是小优化,嵌套深了还是不如计算属性清晰。

内容的提问来源于stack exchange,提问作者Florian Motteau

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 05:03:23