Vue 路由 路由守卫

路由守卫
正如其名, vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。简单来说,就是在路由跳转
时候的一些钩子,当从一个页面跳转到另一个页面时,可以在跳转前、中、后做一些事情。
当你打开一个页面的前后需要去干什么。
每个守卫方法接收参数:
  • to:即将要进入的目标,是一个路由对象
  • from:当前导航正要离开的路由,也是一个路由对象
  • next:可选,是一个方法,直接进入下一个路由
你可以使用 router.beforeEach 注册一个全局前置守卫,当一个导航触发时,就会异步执行这个回调函数。

to是指从哪个页面来,from代表从根目录来。to:从哪来  from:到哪去    

//2.创建路由实例并传递上面路由对象routes
    const router = createRouter({
//路由的一种前端展现方式,通常使用这个就行了
        history: createWebHistory(),
        routes
  }
)

//定义前置路由守卫。进入某个页面之前需要干什么
router.beforeEach((to,from,next) => {
    console.log(to)
    console.log(from)
})

router.beforeEach((to, from, next) => {
//如果用户访问登录页,直接放行
    if(to.path == '/login') {
        return next()
}

const token = '' //模拟token,正常是从本地cookie或localstorage中获取

if (token) {
    return next() //如果有token,则正常跳转访问
} else {
    return next('/login') //如果没有token,跳转到登录页
}
})

一.全局守卫

1.全局前置守卫

语法:

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

参数说明:
to:进入到哪个路由去
from:从哪个路由离开
next:函数,决定是否展示你要看到的路由页面。

示例:
main.js 中设置全局守卫

  • 在main.js中,有一个路由实例化对象router。在main.js中设置守卫已是全局守卫。
  • 如下,判断to.path当前将要进入的路径是否为登录或注册,如果是就执行next(),展示当前界面。如果不是,就弹出alert,然后移至登录界面。
  • 这样就可实现,用户在未登录状态下,展示的一直是登录界面。

router.beforeEach((to,from,next)=>{
  if(to.path == '/login' || to.path == '/register'){
    next();
  }else{
    alert('您还没有登录,请先登录');
    next('/login');
  }})

猜你喜欢

转载自blog.csdn.net/qq_34556414/article/details/132086651