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

Nuxt中useFetch在props参数bar变化时不自动重新请求的问题求助

Nuxt中useFetch在props参数bar变化时不自动重新请求的问题求助

我最近在Nuxt项目里遇到了一个 reactivity 相关的问题,想请大家帮忙看看。

先给大家看下我的代码场景:
首先是应用根组件,我用Nuxt UI的日历组件来处理当前选中的日期:

<script setup lang="ts">
import { today, getLocalTimeZone } from '@internationalized/date';

const foo = 'some-id'; // 实际是页面参数,这里简化处理

const currentSelectedDate = shallowRef(today(getLocalTimeZone()));

const currentSelectedISODate = computed(() => {
  return currentSelectedDate.value.toString();
});
</script>

<template>
  <UApp>
    <UCalendar v-model:model-value="currentSelectedDate" />
    <Child :foo="foo" :bar="currentSelectedISODate" />
  </UApp>
</template>

然后我有一个子组件,接收foo和bar作为props,并且用useFetch请求API:

<script setup lang="ts">
const { foo, bar } = defineProps<{
  foo: string;
  bar: string;
}>();

// 当bar(ISO日期)变化时,不会重新发起请求
const { data, pending, error } = await useFetch(`/api/${foo}/${bar}`);
</script>

<template>
  <UCard>
    <template #header> Foo: {{ foo }} </template>
    <template #footer> Bar: {{ bar }} </template>
  </UCard>
  <UCard>
    <template #header> data: {{ data }} </template>
    <div>pending: {{ pending }}</div>
    <template #footer> error: {{ error }} </template>
  </UCard>
</template>

API端点我放在/api/[foo]/[bar].get.ts,代码很简单:

export default defineEventHandler(async (event) => {
  return new Date().toISOString();
});

现在的问题是:我能看到子组件的bar props会随着日历选中日期的变化而更新,但是useFetch却不会重新发起请求——不管选哪天,data都不会变,也看不到新的API调用,相当于useFetch失去了 reactivity。

我正在做一个沙箱来复现这个问题,想请教大家,我该怎么处理才能让useFetch在bar变化时自动重新请求呢?

备注:内容来源于stack exchange,提问作者m477h145h3rm53n

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 18:12:58