Having trouble with router.push in Vue3 and Vuex4?

Encountering some issues with Vue 3 and Vuex. Attempting to redirect users when logged in within my Vuex file, but the redirection is not happening as expected. No errors are being returned, only a link change without actually redirecting to another page.

The action in question looks like this;

actions: {
        async login(commit: any, payload: any ) {
            const cookie_token  = useCookies();

            API.post('/login', {
                email: payload.email.value,
                password: payload.password.value
            })
                .then((response: any) => {
                    notif.success('Welcome back, ' + response.data.player.name)
                    cookie.set('user', response.data)
                    commit.commit('loginSuccess', response.data)

                    router.push({
                      name: 'index',
                    })

                }).catch((e) => (
                    console.log(e.message)
                )
            )
        }
    },

The issue seems to lie in the router where routes are defined.

Here's the complete router file:

import {
  createRouter as createClientRouter,
  createWebHistory,
} from 'vue-router'
import * as NProgress from 'nprogress'

// import routes from 'pages-generated'


import type { RouteRecordRaw } from "vue-router";

// Then we can define our routes
const routes: RouteRecordRaw[] = [
  // This is a simple route
  {
    component: () => import("/@src/pages/index.vue"),
    name: "index",
    path: "/",
    props: true,
  },
  {
    component: () => import("/@src/pages/auth.vue"),
    path: "/auth",
    props: true,
    children: [
      {
        component: () => import("/@src/pages/auth/login.vue"),
        name: "auth-login",
        path: "login-1",
        props: true,
      },
      {
        component: () => import("/@src/pages/auth/login.vue"),
        name: "auth-signup",
        path: "singup",
        props: true,
      },
    ],
  },
  {
    component: () => import("/@src/pages/[...all].vue"),
    name: "404",
    path: "/:all(.*)",
    props: true,
  },
];

export function createRouter() {
  const router = createClientRouter({
    history: createWebHistory(),
    routes,
  })

  /**
   * Handle NProgress display on-page changes
   */
  router.beforeEach(() => {
    NProgress.start()
  })
  router.afterEach(() => {
    NProgress.done()
  })

  return router
}

export default createRouter()

It's worth noting that other files are functioning correctly, and while I can see the router being triggered here, it is not changing the page. The Vuex functionality seems to be the cause of the issue. Despite it not working, there are no error messages being displayed. Why might this be?

Answer №1

To avoid creating multiple instances of Vue Router, make sure to export the same router instance instead of generating a new one each time it is called.

Consider using the following code for better results:

import {
  createRouter,
  createWebHistory,
} from 'vue-router'
import * as NProgress from 'nprogress'
import type { RouteRecordRaw } from "vue-router";

const routes: RouteRecordRaw[] = [
  // your routes here...
];

let router;

export function useRouter() {
  if (!router) {
    router = createRouter({
      history: createWebHistory(),
      routes,
    })

    router.beforeEach(() => {
      NProgress.start()
    })
    router.afterEach(() => {
      NProgress.done()
    })
  }
  return router
}

The router instance is stored in the outer scope to ensure you always retrieve the same instance by calling useRouter().
Use it like this:

import { useRouter } from '../path/to/router'
const router = useRouter();

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

Did I accidentally overlook a tag for this stylish stripe mesh Gradient design?

I've been attempting to replicate the striped animated Gradient mesh using whatamesh.vercel.app. I've set up the JS file, inserted all the gist code into it, and placed everything in the correct locations, but unfortunately, it's not functio ...

Using jQuery to create a dynamically moving div that forms an endless wall

In order to create a continuous wall that pulls text from a database and displays it, I've developed the following code: $(function() { var x = 0; var y = 100.0; var z=0; setInterval(function() { x -= 0.1; y -= 0.1; ...

The loss of Webgl context that remains unrecovered

I am facing an issue with the loss and restoration of webgl context. My application is quite complex, containing a lot of data, graphs, lists, and maps. Within the map section, I utilize webGL to ensure optimal performance. My code effectively manages th ...

Leveraging jQuery to interact with MySQL database in PHP Laravel framework

I seem to have hit a roadblock with my database, which is quite intricate. Here's the breakdown of the tables used for the questions: product - contains product details such as shoes productattribute - houses different variations of products like bl ...

Steps for embedding a function within another function

One method I know is by using this hack: function executeFunction(func){ setInterval(func,0); } executeFunction("newFunction()"); However, I am searching for a more elegant solution. ...

Utilize .map function to format a date string and generate a table

I am currently utilizing .map along with React in order to generate a table using a coupons object. My goal is to format a date string into the "mm/dd/yyyy" format, with coupon.starts_at typically being set as coupon.starts_at = "2013-08-03T02:00:00Z" I h ...

Issue: Child Pages not found in Nuxt RoutingDescription: When navigating

Currently working on a Nuxt application that utilizes the WordPress REST API to fetch content. While my other routes are functioning correctly, I am facing challenges with nested pages. The structure I have implemented in my Nuxt app is as follows: pages ...

"Create a real-time chat application using Vue and Feathers.js to display incoming messages

Currently in the process of developing a chat application using feathers.js for the backend and Vue for the frontend. Progress has been smooth so far, with successful connections to a mongoose DB where messages sent in the app are stored. However, encounte ...

Displaying information in ejs format

I am currently working on a project to develop a basic webpage that requires the user to input a specific time and then click on submit. Once submitted, I want the relevant data linked to that input to be displayed on the webpage. Upon clicking the submit ...

What is the reason that accessing array elements with negative indices is significantly slower compared to accessing elements with

Let's explore a JavaScript performance test: const iterations = new Array(10 ** 7); var x = 0; var i = iterations.length + 1; console.time('negative'); while (--i) { x += iterations[-i]; } console.timeEnd('negative'); var y = ...

Reorganizing Arrays in Javascript: A How-To Guide

I have an array in JavaScript called var rows. [ { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81f4f2e4f3b0c1e4f9e0ecf1ede4afe2eeec">[email protected]</a>' }, { email: '<a hre ...

Can we split the PHP Photo Gallery into a second page after displaying 12 images?

I recently developed a simple PHP photo gallery for my website that pulls data from a MySQL database. By using a while loop, I am able to display three images (from ID 1 to 3) in a single row, continuing this pattern until a total of 12 images are shown. ...

Every time I try to launch NPM start, an error pops up on my screen

Whenever I try to execute the command: npm start An error message pops up saying: npm ERR! missing script: start This is what my package.json file looks like: { "name": "react-app", "version": "0.1.0", "private": true, "dependencies": { " ...

What is the best way to ensure a div occupies the full height within a grid layout?

https://i.sstatic.net/awwxE.png Looking at the image provided, I am seeking a way to make the top left image occupy the entire height just like the neighboring div in the first row of the grid. Is there a way to achieve this? The desired outcome should b ...

A guide to duplicating the Mesh of a Line entity using THREE.js

I am attempting to create a for loop consisting of 10 lines. However, I am encountering an error with line.Clone() as it is unable to find any mesh to clone from. If you have any insights on how to access the mesh of a line, please share. Below is the cod ...

Angular Kendo dropdownlist and input textbox are not working together as anticipated

I'm looking to implement a dropdown list similar to Google search using Kendo Angular. However, I've encountered an issue where entering text in the textbox and pressing "Enter" passes the first matching value from the dropdown list to my compone ...

After compiling my project using npm run dev, Vue 3 throws an error

Hey there! I recently attempted to install the necessary dependencies for a Vue.JS app repository by running npm install. Subsequently, I launched the Vue.JS app using npm run dev. However, upon execution, an error popped up in the terminal: PS G:\ma ...

Discover the Elements that have been incorporated through the use of JavaScript

I am facing an issue with my ASP site where users can add Label elements. The problem is I am not able to track the labels that were added or their IDs. All I know is that they will be inside the Panel called pnl_Added. Once the user has finished adding la ...

I'm facing an issue where Typescript isn't recognizing Jest types

The Challenge Setting up a TypeScript project with Jest has been proving difficult for me. It seems that TypeScript is not recognizing the Jest types from @types/jest, resulting in an error message like this: Cannot find name 'test'. Do you nee ...

Navigating Angular.js: finding my way to the endpoint paths

Despite my best efforts and extensive research, I find myself in need of assistance! I have a web application that utilizes node and express on the server side, with Angular on the client side. My issue lies with angular routing. IMPORTANT DETAILS My cur ...