Nuxt的 useFetch在 URL参数变化时不会重新获取数据
给定这个Nuxt应用根组件的示例代码,使用Nuxt UI日历组件来处理当前选中的日期
<script setup lang="ts">
import { today, getLocalTimeZone } from '@internationalized/date';
const foo = 'some-id'; // this is a page parameter but for the sake of simplicity...
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>
现在我有一个子组件,它需要把这些值作为props传入
<script setup lang="ts">
const { foo, bar } = defineProps<{
foo: string;
bar: string;
}>();
// does not refetch on bar ( isoDate ) change
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/[foo]/[bar].get.ts
export default defineEventHandler(async (event) => {
return new Date().toISOString();
});
我可以看到props会改变,但 useFetch 不会在 bar 改变时重新获取数据。每当我选择另一天时,我可以看到 bar 会改变,但 data 从不改变。此外没有API调用,因此 useFetch 不再具备响应性。
我目前正在一个沙盒环境中练习
https://stackblitz.com/edit/nuxt-starter-a1s1dox4?file=app%2Fapp.vue
如何处理这种响应性?
解决方案
这就是 useFetch 将URL作为ref或 getter函数接收的原因;这是组合式函数的一种常见写法,因此一个组合式函数可以用 toValue 将其解包并监听一个值。
它应该是这样的:
const { data, pending, error } = await useFetch(() => `/api/${foo}/${bar}`);
请注意,foo 和 bar 的响应性依赖于 响应式的props解构,并取决于Vue的版本和编译器配置。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。