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

Nuxt3:用户交互时如何刷新useFetch获取的评论数据?

解决方案

核心思路

用响应式变量控制请求URL,让Nuxt3的useFetch自动监听变量变化并重新请求数据,无需手动重复调用useFetch。

修改 Comments.vue

<template>
  <section>
    <header>
      <CommentsSort @sort-comments-event="sortComments" />
    </header>
    <div>
      <aside>
        <CommentsAdd @refresh-comments-list-on-add="refreshCommentsList" />
      </aside>

      <div>
        <AppSpinner v-if="pending" />
        <CommentsList :comments="data" v-else />
      </div>
    </div>
  </section>
</template>

<script setup>
const route = useRoute()
// 定义响应式排序参数,初始为'newest'
const sortBy = ref('newest')

// 动态生成请求URL,依赖sortBy和文章ID,变量变化时自动重请求
const { pending, data, refresh } = await useFetch(() => 
  `/api/comments/${sortBy.value}/${route.params.id}`
)

const refreshCommentsList = () => {
  refresh()
}

// 排序逻辑简化为更新sortBy变量
const sortComments = (value) => {
  sortBy.value = value
}

// 删除原无效的onMounted调用(原代码中e未定义)
</script>

保留原CommentsSort.vue的emit逻辑(无需修改)

<template>
  <select
    v-model="selected"
    @change="sortCommentsEvent"
  >
    <option disabled value="">Sort by</option>
    <option value="newest">Newest</option>
    <option value="oldest">Oldest</option>
    <!-- <option value="likes">Likes</option> -->
  </select>
</template>

<script setup>
const emits = defineEmits(['sort-comments-event'])
const selected = ref('newest')

const sortCommentsEvent = () => {
  emits('sort-comments-event', selected.value)
}
</script>

关键说明

  1. 自动重请求机制:useFetch接收函数返回URL时,会自动监听函数内的响应式变量(sortBy.value、route.params.id),变量变化时自动触发新请求,无需手动重复调用useFetch。
  2. 修复无效代码:原onMounted里的sortComments(e)属于无效代码(e未定义),直接删除即可。
  3. 状态一致性:新增评论后调用refresh(),会使用当前sortBy参数重新请求,保证排序状态和最新评论同步。
  4. 扩展排序规则:后续添加likes排序时,只需在CommentsSort里加选项,useFetch会自动处理对应的URL请求,无需额外修改请求逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 14:36:20