Nuxt3中useFetch动态请求失效,useAsyncData正常是否为框架Bug?
为什么Nuxt中useFetch无法处理动态参数请求,而useAsyncData可以?
这不是Nuxt的Bug,是你对useFetch的响应式参数处理方式理解有误。
问题原因
你当前的useFetch写法中,query: { count: count.value }只会在组件初始化时读取一次count.value的值,之后即使count更新,这个配置不会自动同步最新值。而useAsyncData的回调函数每次执行(包括调用refresh()时)都会重新读取count.value,所以能获取到最新参数。
正确的useFetch使用方式
要让useFetch响应参数变化,有三种常见方案:
将query配置为响应式对象
直接传入ref或者reactive对象作为query,useFetch会自动跟踪其变化:const count = ref(1); const queryParams = ref({ count: count.value }); const { data, refresh } = await useFetch(`/api/hello`, { query: queryParams, }); function add() { count.value++; queryParams.value.count = count.value; refresh(); }在refresh时手动传递新参数
调用refresh()时可以传入新的请求配置,覆盖原有参数:const count = ref(1); const { data, refresh } = await useFetch(`/api/hello`, { query: { count: count.value }, }); function add() { count.value++; refresh({ query: { count: count.value } }); }使用函数返回query参数(Nuxt 3.3+支持)
将query设为函数,每次请求时会执行函数获取最新参数:const count = ref(1); const { data, refresh } = await useFetch(`/api/hello`, { query: () => ({ count: count.value }), }); function add() { count.value++; refresh(); }
验证修正后的代码
以第三种方案为例,完整可运行代码如下:
<script setup> const count = ref(1); // 现在可以正常工作了 const { data, refresh } = await useFetch(`/api/hello`, { query: () => ({ count: count.value }), }); function add() { count.value++; refresh(); } </script> <template> <NuxtExampleLayout example="composables/use-fetch"> <div> Fetch result: <pre class="text-left"><code>{{ data }}</code></pre> <NButton @click="count++"> + </NButton> <NButton @click="add">add</NButton> </div> </NuxtExampleLayout> </template>
内容的提问来源于stack exchange,提问作者Johnson
相关产品推荐
相关产品推荐

