首页 > 解决方案 > Vue JS(router.beforeEach)无法将异常转换为字符串

问题描述

我正在尝试使用router.beforeEachwith localStorage。如果有数据localStorage,我想跳过主页。如果没有数据,进入首页。我可以用 打印数据console.log,但路由器进程失败

[vue-router] 路由导航期间未捕获的错误 > 无法将异常转换为字符串。

如何控制导航?

我的router.js

Vue.use(Router);

const router = new Router({
    routes: [{
            path: '/',
            name: 'index',
            components: {
                default: Index,
                header: MainNavbar
            },
            props: {
                header: {
                    colorOnScroll: 400
                }
            }
        },
        {
            path: '/landing',
            name: 'landing',
            components: {
                default: Landing,
                header: MainNavbar,
                footer: MainFooter
            },
            props: {
                header: {
                    colorOnScroll: 400
                },
                footer: {
                    backgroundColor: 'black'
                }
            }
        },
        {
            path: '/login',
            name: 'login',
            components: {
                default: Login,
                header: MainNavbar
            },
            props: {
                header: {
                    colorOnScroll: 400
                }
            }
        },
        {
            path: '/profile',
            name: 'profile',
            components: {
                default: Profile,
                header: MainNavbar,
                footer: MainFooter
            },
            props: {
                header: {
                    colorOnScroll: 400
                },
                footer: {
                    backgroundColor: 'black'
                }
            }
        }
    ],
    scrollBehavior: to => {
        if (to.hash) {
            return {
                selector: to.hash
            };
        } else {
            return {
                x: 0,
                y: 0
            };
        }
    }
});

router.beforeEach((to, from, next) => {
    let adres = JSON.parse(localStorage.getItem('adres'));
    if (!adres) {
        next('/');
    } else {
        next('/login');
    }
});

export default router;

本地数据示例:

{  
   "id":1,
   "adi":"Demo",
   "soyadi":"Sef",
   "telefon":"05322375277",
   "adres":"Girne Mahallesi 6022 Sk. No:22 Kahta/Adıyaman",
   "fotograf":"http://localhost:8000/media/kullanici/sef/demosef/chef-1.jpg"
}

标签: vue.jsvuejs2vue-componentvue-router

解决方案


您正在创建一个无限循环,您的beforeEach守卫会被一遍又一遍地触发。在beforeEach它检查 localStorage 中是否有地址并重定向到/or 或/login。然后在您输入新路由之前再次beforeEach调用并检查是否有地址并重定向。该过程无限重复。您需要next()在警卫中的某处不带任何参数的情况下调beforeEach用以确认正常导航。所以你可能想做这样的事情..

router.beforeEach((to, from, next) => {
  if (to.path == '/') {  // If we are entering the homepage.
    let adres = JSON.parse(localStorage.getItem('adres'));
    if (!adres) {
      next();
    } else {
      next('/login');
    }
  } else {  // Not entering the homepage. Proceed as normal.
    next()
  }
});

推荐阅读