【问题标题】:Why is router.push not working? [Vue3] [Vuex4]为什么 router.push 不起作用? [Vue 3] [Vuex 4]
【发布时间】:2022-01-16 20:46:02
【问题描述】:

我对 Vue 3 和 Vuex 有一些问题。 我在登录我的 Vuex 文件时尝试重定向用户,但它没有按预期工作。 它没有返回任何错误,它正在更改链接,但没有重定向到另一个页面。

我的动作是这样的;

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

路由器正在获取定义路由的文件。

这是我的完整路由器文件:

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()

请记住它正在处理其他文件,我可以看到这里触发了路由器,但没有更改页面,只有在 vuex 上不起作用。如果它不起作用,为什么没有错误?

【问题讨论】:

    标签: javascript vue.js vuex vuejs3


    【解决方案1】:

    您正在创建多个 Vue Router 实例。您应该导出相同的 router 实例,而不是每次调用时都创建新实例的函数。

    以下代码可能会产生预期的结果:

    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
    }

    我将router 实例放置在外部作用域中,因此在调用useRouter() 时总是会得到相同的实例。
    使用它:

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

    【讨论】:

    • 是的,我也注意到了这一点。现在我有类似的错误: Uncaught SyntaxError: The requested module '/src/router.ts' does not provide an export named 'createRouter'
    • 是的,我把函数的名字从createRouter改成了useRouter。因为你不是在创建一个新的,你正在使用已经创建的。将其命名为 createRouter,恕我直言,没有意义。
    • 仍有错误 Uncaught SyntaxError: The requested module '/src/router.ts' does not provide an export named 'createRouter'
    • 在你的代码中有import { createRouter } from '/src/router.ts'(控制台会告诉你确切的位置)。去那里并用useRouter替换createRouter。注意:可能不止一个地方。您必须在每个地方重命名该功能。现在,很简单,您可以保留导出函数的名称 createRouter(并将导入的函数重命名为 createClientRouter,就像以前一样),但是,据我估计,该名称是错误的,因为您的函数确实不是创建一个新的路由器实例。它返回已经创建的。
    • 谢谢
    猜你喜欢
    • 2021-09-12
    • 2021-06-24
    • 2018-11-10
    • 2022-08-03
    • 2021-12-06
    • 1970-01-01
    • 2019-03-18
    • 2021-12-22
    • 2019-03-29
    相关资源
    最近更新 更多