Encountering an Issue with Vue 3 and Vue Router 4: Uncaught TypeError - Trying to Access Undefined Properties (specifically 'push')

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>

Answer №1

Resolved the issue.

The const router = useRouter(); line should be placed outside of the enterChat function. It seems that you cannot instantiate the router inside the same function where you intend to use it.

Here is the correct implementation:

const router = useRouter(); //<-- declaring router outside function: RIGHT
const enterChat = () => {
  router.push({ name: "Chatroom" });
};

And this is incorrect:

const enterChat = () => {
  const router = useRouter();//<-- declaring router inside function: WRONG
  router.push({ name: "Chatroom" });
};

Below is the revised file for your reference:

<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>Already registered? <span @click="showLogin = true">Login</span></p>
    </div>
  </div>
</template>

<script setup lang="ts">
import SignUpFormVue from "@/components/SignUpForm.vue";
import LoginFormVue from "@/components/LoginForm.vue";
import { ref } from "vue";
import { useRouter } from "vue-router";

const showLogin = ref(false);
const router = useRouter();
const enterChat = () => {
  console.log(router);
  router.push({ name: "Chatroom" });
};
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How do I disable the hover and click highlighting effect on a div in Vuetify using v-on in Vue2?

Currently, I have implemented a Vuetify VListItem in a NavigationDrawer with an on click listener that displays a menu in the div below. The menu is functioning properly - opening and closing as expected. However, it highlights on hover/click which I wou ...

What causes the disparity in functionality between simple html and css in an Angular 2 project compared to a vanilla html website?

When incorporating the following html/css into a new Angular project created with Angular CLI using 'ng new ProjectName', I encountered issues. Despite adding the CSS to app.component.css or styles.css and the HTML to app.component.html, the Angu ...

Exploring Angular5 Navigation through Routing

I have been working with Angular routing and I believe that I may not be using it correctly. While it is functional, it seems to be causing issues with the HTML navbars - specifically the Info and Skills tabs. When clicking on Skills, a component popup s ...

Having issues with Vue js increment operator not yielding the desired results

What could be causing the below Vue.js code to output 102? <html> <head> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> </head> <body> <div id = "intro&qu ...

The beauty of asynchronous GET requests in VueJS

As a newcomer to VueJS, I am exploring how to make a GET request to the GitHub API. Initially, I made a request to sort users by follower count, resulting in an array ordered in descending order of user logins. Following that, I sent another GET request to ...

What potential drawbacks come with utilizing the OOP approach in both JavaScript and React?

While working on an internal project, I found myself creating a base system and implementing a custom form structure using TypeScript with an OOP approach. class Form extends React.Component {} abstract class FormElement extends React.Component<{valid ...

Delay the execution of @mouseover in Vue: a guide to managing scope

Looking to implement an action only when the user has hovered over a div for at least 1 second. Here's how it's set up: <div @mouseover="trigger"></div> In the script section: data() { return { hovered: false } } m ...

What are the steps to start a basic Vue compilation in Gulp?

In my current workflow, I rely on gulp and have not yet incorporated webpack or browserify. However, I have discovered that to compile Vue 2.x components, one of these tools is required as there are no actively maintained methods for compiling Vue componen ...

What is the best way to access the input element of ng-content from the parent component?

Creating a unique component in the following structure <div class="custom-search-field" [ngClass]="{'expanding': expanding}"> <ng-content></ng-content> </div> When using this component, users are expected to include ...

Navigate to a new route in Vue Router and pass parameters as part of the navigation

I have a component that handles programmatic routing based on external data retrieved in the App.vue component and passed down to child components as props. In the child component, the external data is accessed like this: props: { externalData: Array ...

Arrange the items that are missing from Array B to be located at the bottom of Array A, organized in a file tree structure

I have two arrays containing different types of objects. Each object in the arrays has a title assigned to it. My goal is to compare these two arrays based on their titles and move any files that are not included in the bottom part of the fileStructure arr ...

In Angular 4, the Bootstrap modal now only opens after a double click instead of opening on the first click

Working on an eCommerce application, there is a cart icon that triggers a modal screen displaying user-selected product data when clicked. However, the issue I'm facing is that upon initial page load, the modal screen opens only after double-clicking; ...

What could be the reason for the absence of a TypeScript error in this situation?

Why is it that the code below (inside an arbitrary Class) does not show a TypeScript error in VSCode as expected? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... * ...

Is there a way to execute a method from a child component in VueJS?

I'm trying to figure out how to make a parent component trigger a method in a child component when a button is clicked. Here's an example of what I have: Parent <template> <child-component></child-component> <button @clic ...

Tips for successfully passing function variables as parameters to Angular 2 HTTP subscribe callbacks

I attempted this.propositionService.addProposition(this.proposition) .subscribe(this.addSuccessCallback, this.addFailureCallback); The issue I am encountering is that both addSuccessCallback and addFailureCallback do not have acces ...

Challenge with Vue fetching data

I need to make an update request using fetch. Here is the code snippet: methods: { updateData() { fetch("http://localhost:3000/selectedData", { method: "PATCH", headers: { "Content-Type": & ...

Despite passing the same dependency to other services, the dependencies in the constructor of an Angular2 Service are still undefined

To successfully integrate the "org-agents-service" into the "org-agents-component," I need to resolve some dependencies related to the required api-service. Other components and services in the hierarchy are also utilizing this api-service, which acts as a ...

Angular - The 'options' property is not found in the 'HTMLOptionElement' type

Currently, I am attempting to modify the choices in a dropdown menu based on the selection made from another dropdown. This problem led me to come across a helpful resource on a website called "Form Select Change Dynamic List Option Elements Tutorial". How ...

What is the best practice for inserting typescript definitions and writing them when the object already has a pre-existing definition?

Apologies for this question, as I am struggling to find the necessary information due to my limited understanding of Typescript. I have integrated a jquery plugin called typeahead and added a global variable named bound on the window object for communicati ...

Turning XSD into TypeScript code

Stumbling upon this tool called CXSD, I was intrigued. The documentation describes cxsd as a streaming XSD parser and XML parser generator designed for Node.js and TypeScript (optional but highly recommended). It seemed like the perfect solution for my ne ...