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
相关产品推荐
相关产品推荐

