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

Vue 3函数式组件中如何访问Router?useRouter返回undefined

解决Vue3函数式组件中useRouter返回undefined的问题

问题原因

Vue3的函数式组件(FunctionalComponent)没有独立的组件实例,而useRouter这类Composition API钩子必须依赖组件实例的上下文才能正常工作,直接调用自然会返回undefined。

解决方案

方案1:改用普通Composition API组件(推荐)

函数式组件更适合纯渲染、无状态的场景,涉及状态管理和路由跳转的逻辑,用普通组件更贴合Vue3的开发习惯:

<script setup>
import { useRouter } from "vue-router";
import { useUserProfileStore } from "./stores/UserProfile";

const userProfileStore = useUserProfileStore();
const router = useRouter();

// 组件挂载后执行数据填充和跳转
userProfileStore.randomData();
router.replace("/");
</script>

<template>
  <div>正在跳转...</div>
</template>

方案2:在函数式组件中手动注入Router实例

如果一定要保留函数式组件结构,可以通过inject手动获取全局注入的Router实例:

import { FunctionalComponent, inject } from "vue";
import { Router } from "vue-router";
import { useUserProfileStore } from "./stores/UserProfile";

const Prefill: FunctionalComponent<{}> = (props, { inject }) => {
  const userProfileStore = useUserProfileStore();
  // 从全局上下文注入Router实例
  const router = inject<Router>("router");
  
  userProfileStore.randomData();
  // 使用可选链避免router为undefined时报错
  router?.replace("/");
};

Prefill.props = [];
Prefill.emits = [];
export default Prefill;

注意:此方法需要确保你已经在项目入口(如main.ts)中通过app.use(router)完成了Router的全局注册。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:32:06