没有登录?赶快去登录!!

929 阅读1分钟

Vue的路由守卫

效果讲解:

1.png

2.png 搭建好项目后,打开router下的index.js文件

image.png 需要用到Vue里面的钩子函数——beforeEach
这个函数的作用是:一般用来做一些进入页面的限制,就是当没有登录的时候,想要进入某一个页面,这个时候路由强制跳转到登录页面,说白了,就是路由守卫。
router.beforeEach里面可以传入三个参数:

router.beforeEach((to, from, next)=>{
    console.log(to)
})

to表示我要跳转的目标路由对应的参数。

image.png from表示来自那个路由,就是操作路由跳转之前的,即将离开的路由对应的参数。
next是一个回调函数,一定要调用next方法来resolve这个钩子函数。
这个时候,可以在这个钩子函数里面做一些守卫的操作。

router.beforeEach((to, from, next)=>{
    console.log(to)
    if(to.path==="/login"){
        //  "/login"是登录页面的路由
        return next()
    }
})

如果要去的页面是登录页面,直接调用next()函数,直接跳转到登录页面。
登录后,需要在Cookie或者本地(sessionStorage,locaStorage)中存入一个参数,比如userId。

router.beforeEach((to, from, next)=>{
    console.log(to)
    if(to.path==="/login"){
        return next()
    }
    const userId = sessionStorage.getItem("userId")
    //  当没有userId的时候,跳转到登录页面
    if(!userId){
        return next("/login")
    }
    //  有userId  直接跳转想要去的页面 重新调用next()函数
    next()
})

※※※※※※注意router.beforeEach()的位置,如果代码写的位置不对,就会出现

SQ52)VEY4`GY{)LCVDOZMK1.png

router.beforeEach()一般都是放在

image.png 实例化和抛出函数的中间。

image.png