最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is router.push not working? [Vue3] [Vuex4] - Stack Overflow

programmeradmin1浏览0评论

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(mit: any, payload: any ) {
            const cookie_token  = useCookies();

            API.post('/login', {
                email: payload.email.value,
                password: payload.password.value
            })
                .then((response: any) => {
                    notif.success('Wele back, ' + response.data.player.name)
                    cookie.set('user', response.data)
                    mitmit('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
  {
    ponent: () => import("/@src/pages/index.vue"),
    name: "index",
    path: "/",
    props: true,
  },
  {
    ponent: () => import("/@src/pages/auth.vue"),
    path: "/auth",
    props: true,
    children: [
      {
        ponent: () => import("/@src/pages/auth/login.vue"),
        name: "auth-login",
        path: "login-1",
        props: true,
      },
      {
        ponent: () => import("/@src/pages/auth/login.vue"),
        name: "auth-signup",
        path: "singup",
        props: true,
      },
    ],
  },
  {
    ponent: () => 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?

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(mit: any, payload: any ) {
            const cookie_token  = useCookies();

            API.post('/login', {
                email: payload.email.value,
                password: payload.password.value
            })
                .then((response: any) => {
                    notif.success('Wele back, ' + response.data.player.name)
                    cookie.set('user', response.data)
                    mit.mit('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
  {
    ponent: () => import("/@src/pages/index.vue"),
    name: "index",
    path: "/",
    props: true,
  },
  {
    ponent: () => import("/@src/pages/auth.vue"),
    path: "/auth",
    props: true,
    children: [
      {
        ponent: () => import("/@src/pages/auth/login.vue"),
        name: "auth-login",
        path: "login-1",
        props: true,
      },
      {
        ponent: () => import("/@src/pages/auth/login.vue"),
        name: "auth-signup",
        path: "singup",
        props: true,
      },
    ],
  },
  {
    ponent: () => 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?

Share Improve this question edited Dec 13, 2021 at 12:39 tao 90.5k17 gold badges133 silver badges173 bronze badges asked Dec 13, 2021 at 11:07 Rade IlievRade Iliev 2395 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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 oute:

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();
发布评论

评论列表(0)

  1. 暂无评论