I'm currently working with Vue 3, Vue Router 4, and TypeScript in my project. However, I've encountered an issue while trying to utilize router.push()
. Every time I attempt this, I receive a console error stating:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'push')
.
What could be causing this error in my code?
UPDATE: Upon running console.log(router);
, I noticed that it returns undefined
. This seems to be the root cause of the problem, but why is the router returning undefined and what steps can I take to rectify this issue?
Below is the code snippet from my router/index.ts
:
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
const routes: Array<RouteRecordRaw> = [
{
path: "/",
name: "Welcome",
component: () =>
import(/* webpackChunkName: "Welcome" */ "../views/Welcome.vue"),
},
{
path: "/chatroom",
name: "Chatroom",
component: () =>
import(/* webpackChunkName: "Chatroom" */ "../views/ChatRoom.vue"),
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
export default router;
The following code block showcases the Vue file where the router.push()
error occurs. I have attempted using both a named route and a path, only to encounter the same error:
<template>
<div class="welcome container">
<p>Welcome</p>
<div v-if="showLogin">
<LoginFormVue @loggedIn="enterChat" />
<p>No account yet? <span @click="showLogin = false">Signup</span></p>
</div>
<div v-else>
<SignUpFormVue @signedUp="enterChat" />
<p>Alredy registered? <span @click="showLogin = true">Login</span></p>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from "vue";
import SignUpFormVue from "@/components/SignUpForm.vue";
import LoginFormVue from "@/components/LoginForm.vue";
import { useRouter } from "vue-router";
const showLogin = ref(false);
const enterChat = () => {
const router = useRouter();
console.log(router);
router.push({ name: "Chatroom" });
};
</script>