首页 > 解决方案 > 如果在 router.js vuejs 中条件为真,如何在其他路由上重定向

问题描述

我在 vuejs 中有多重身份验证应用程序。因此,在 router.js 中,我检查了如果客户登录它应该重定向到客户仪表板,如果管理员登录它应该重定向到管理仪表板

在 router.js 中,我在 beforeEach() 中实现了它。但它多次重定向它会产生错误。

这是我的 router.js beforeEachFunction()

if (Object.keys(store.state.AppActiveUser).length !== 0 && !store.state.AppActiveUser.is_customer ) {
       
        if (!to.meta.authRequired && auth.isAuthenticated()) {
            router.push({ path: '/dashboard', name: 'dashboard', component: './views/DashboardAnalytics.vue' })
        }

    } if (Object.keys(store.state.AppActiveUser).length !== 0 && store.state.AppActiveUser.is_customer) {

        if (!to.meta.authRequired && auth.isAuthenticated()) {
            router.push({ path: '/customer/dashboard', name: 'customer-dashboard', component: '@/views/apps/customerComponents/dashboard/DashboardAnalytics.vue' })
        }
    }

这是错误

Uncaught (in promise) RangeError: Maximum call stack size exceeded
    at iterator (app.js:51760)
    at step (app.js:51410)
    at app.js:51411
    at app.js:51785
    at app.js:98591
    at iterator (app.js:51763)
    at step (app.js:51410)
    at runQueue (app.js:51418)
    at HTML5History.confirmTransition (app.js:51793)
    at HTML5History.transitionTo (app.js:51666)

实际上,在到达 beforeEach 之前,我在路由器中推送路由取决于客户或管理员。

现在,当我转到客户路线时,它没有 /dashboard 路线,所以我认为它一次又一次地尝试

标签: vue.jsvuejs2vue-routervue-router4

解决方案


所以你有这个错误的原因是因为每次 Vue 路由器尝试切换到新路由时,你告诉它再次切换到新路由。

解决方案是让 Vue Router 在您到达所需目的地时完成它的工作。

if (Object.keys(store.state.AppActiveUser).length !== 0 && !store.state.AppActiveUser.is_customer ) {
        var am_i_there_yet = to.name == 'dashboard';
        if (!to.meta.authRequired && auth.isAuthenticated() && !am_i_there_yet) {
            router.push({ path: '/dashboard', name: 'dashboard', component: './views/DashboardAnalytics.vue' })
        }

    } if (Object.keys(store.state.AppActiveUser).length !== 0 && store.state.AppActiveUser.is_customer) {
        var am_i_there_yet = to.name == 'customer-dashboard';

        if (!to.meta.authRequired && auth.isAuthenticated() && !am_i_there_yet) {
            router.push({ path: '/customer/dashboard', name: 'customer-dashboard', component: '@/views/apps/customerComponents/dashboard/DashboardAnalytics.vue' })
        }
    }

这是一个解决相同问题的相关问题:为什么我会收到错误消息 Maximum call stack size exceeded in Vue Router?


推荐阅读