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

Vue Firebase项目中router未定义问题排查求助

问题排查:Vue3中useRouter返回undefined的解决方案

核心原因

你把useRouter()的调用放在了setup()函数外面的顶级作用域,这违反了Composition API钩子的使用规则——所有Composition API钩子(包括useRouter、useStore等)必须在setup函数内部或者其他Composition API函数内部调用,否则无法获取到Vue的上下文,自然返回undefined。

修正后的代码

<script lang="ts">
import { ref } from "vue";
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
import { useRouter } from "vue-router";

export default {
  name: "SignUp",
  setup() {
    // 将useRouter移至setup内部
    const router = useRouter();
    const email = ref("");
    const password = ref("");

    const signUp = (): void => {
      createUserWithEmailAndPassword(getAuth(), email.value, password.value)
          .then((data) => {
            console.log("Success");
            router.push("/feed");
          })
          .catch((error) => {
            console.log(error.code);
            alert(error.message);
          });
    };

    const signInWithGoogle = (): void => {
      // Add your code to sign in with Google here
    };

    return {
      email,
      password,
      signUp,
      signInWithGoogle
      // 注:router无需返回,仅在setup内部使用即可
    };
  },
};
</script>

额外检查点

  • 确认Vue实例已正确挂载router:
    在main.ts/index.ts中,需确保创建Vue应用时传入router实例,示例代码如下:
    import { createApp } from 'vue'
    import App from './App.vue'
    import router from './router' // 你的router导出文件
    
    createApp(App).use(router).mount('#app')
    
  • 确认vue-router版本适配Vue3:必须使用vue-router@4.x版本,低版本不支持Vue3的Composition API。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 15:15:27