Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

313
Visualizações
Why is router.push not working? [Vue3] [Vuex4]

I have some issues with Vue 3 and Vuex. I'm trying to redirect users when logged in in my Vuex file, but it's not working as expected. It's not returning any errors, it's changing a link, but not redirected to another page.

My action 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)
                )
            )
        }
    },

And the router is getting files where routes are defined.

And here is my full 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()

Have in mind that it's working on other files, and I can see that router is triggered here, but not chaning a page, only on vuex is not working. If it's not working, why there is no error?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You're creating more than one instance of Vue Router. You should export the same router instance, not a function creating a new instance each time it gets called.

The following code will likely yield the desired outcome:

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
}

I'm placing the router instance in the outer scope, so you always get the same instance when calling useRouter().
Consume it using:

import { useRouter } from '../path/to/router'
const router = useRouter();
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda