Route guard in vue

Route guard in vue

Global guard

to: target route
from: current route
next() must call
next(false);//Don’t let go
next(true);//Continue to go
next('/login')//Where to go
next(( path:'/login',params:{},query:{}})// bring some goods

1、在登录界面,登录成功时将username存储在localStorage里面

//前置
router.beforeEach((to,from,next)=>{
//如果要去My或者index页面
  if(to.path=='/My' || to.path=='/index' ){
  //判断l如果ocalStorage里面是否有Username
    if(localStorage.getItem("username")){
   //有用户信息让它继续走
      next(true);
    }else{
      //否则让它跳转到登录界面,跳转到登录界面时,需要把to.path传入,方便在登录成功时跳转到对应界面上
      next({"path":"/Login",query:{"topath":to.path}})
    }
  }else{
  //否则去其他界面时 让它继续走
    next(true);
  }
})

When the login is successful, the following code needs to be added, that is, after the login is successful, the page from the guard will automatically jump to that page after the login is successful

this.$router.push(this.$router.params.topath)

Routing meta information

Under normal circumstances, when we need to guard a lot of pages, or when we want to add guards in the future, we don’t need to modify the logic.

Insert picture description here
Here we need to write a long code in order to simplify the use of routing meta-information.
Insert picture description here
For each routing configuration that needs to be guarded, we only need to add the code in the box above.
Then we only need to write this in the routing guard. As shown below
Insert picture description here

Isn’t that much more convenient?

Rear guard

router.afterEach((to,from)=>{
  //全局后置守卫业务
})

Exclusive routing guard

// src/router/index.js
{
  path: '/user',
  component: User,
  beforeEnter: (to,from,next)=>{ //路由独享守卫 前置 
    console.log('路由独享守卫');
    if(Math.random()<.5){
      next()
    }else{
      next('/login')
    }
  }
 }

Note: Exclusive, no post

Component internal guard

//组件内部钩子
beforeRouteEnter (to, from, next) {//前置
  // 不!能!获取组件实例 `this`
  // 因为当守卫执行前,组件实例还没被创建
},
beforeRouteUpdate (to, from, next) {
  // 在当前路由改变,但是该组件被复用时调用
  // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
  // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
  // 可以访问组件实例 `this`
},
beforeRouteLeave (to, from, next) {//后置
  // 导航离开该组件的对应路由时调用
  // 可以访问组件实例 `this`
}

note:

Exclusive routing guard, guarding the path

The internal guard of the component, the guard is the component

Guess you like

Origin blog.csdn.net/qq_43923146/article/details/109842420