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

如何在VueUse的useFetch的onFetchError中调用useRouter?

问题原因

createFetch 的配置回调(beforeFetch、onFetchError)是在模块级别执行的,不属于任何Vue组件的setup上下文。而useRoute、useRouter这类组合式API必须在组件实例的上下文中调用,否则会返回undefined——这就是你遇到问题的核心原因。

解决方案

直接在模块中导入全局的router实例,绕过组件上下文的限制,同时通过router.currentRoute.value获取当前路由状态:

步骤1:导出全局路由实例

在你的main.ts(或main.js)中,导出创建好的router对象:

// main.js
import { createRouter, createWebHistory } from 'vue-router'
import routes from './routes'

export const router = createRouter({
  history: createWebHistory(),
  routes
})

createApp(App).use(router).mount('#app')

步骤2:修改自定义fetch函数

导入全局router,并调整onFetchError的逻辑:

import { createFetch } from '@vueuse/core'
import { router } from './main' // 对应你的main文件路径
import { useSessionStore } from './stores/session' // 你的Pinia store路径

export const useApiFetch = createFetch({
  baseUrl: import.meta.env.VITE_API_BASE_URL,
  options: {
    beforeFetch({ options }) {
      const { user } = useSessionStore()
      if (user) {
        options.headers.Authorization = `Basic ${user.user_id}:${user.password}`
      }
      return { options }
    },
    onFetchError({ response }) {
      // 通过router.currentRoute.value获取当前路由
      const currentRoute = router.currentRoute.value
      if (currentRoute.name !== 'login' && response?.status === 401) {
        router.push('/login')
      }
    }
  }
})

补充说明

  • 注意onFetchError的参数是一个包含response的对象,需要解构获取;
  • 增加response?.status的可选链判断,避免请求失败无response时抛出错误;
  • 这种方式不需要依赖组件上下文,无论在组件内还是其他组合式函数中调用useApiFetch,都能正常触发路由跳转逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:55:25