Vue routing navigation guard (global guard, routing exclusive guard, component guard)

What is a router guard?

The routing guard is some verification of the routing jump, such as login authentication (no login can not enter the personal center page) and so on.

Route guards are divided into three categories:

  1. Global guard :beforeEach

  2. Guards exclusive to routing :beforeEnter

  3. Guard in the assembly : beforeRouteEnter, beforeRouteUpdate,beforeRouteLeave

Each guard method receives three parameters:

  • to: Destination route to enter (where to go)
  • from: The route to leave (where did it come from)
  • next: Whether to proceed to the next step (do you want to continue)

The specific use of the next function:
Insert picture description here

Global guard

1. Import and mount the VUE routing object in the routing js file

import Router from 'vue-router'

Vue.use(Router)

2. Create a routing instance

Add to the route that needs to be guarded: meta: {permission: true },

const router = new Router({
    
    
  routes: [
    {
    
     path: '/', redirect: '/login' },
    {
    
     path: '/login', component: Login },
    {
    
     path: '/home', component: Home,meta: {
    
     permission: true }}
  ]
})

3. Mount routing and navigation guards

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
    
    
  if (to.meta.permission) {
    
    
    if (sessionStorage.getItem("token")) {
    
    
      next();
    } else {
    
    
      alert("请先登录");
      next("/login");
    }
  } else {
    
    
    next();
  }
});

4. Export routing

export default router

Single router guard

You can do so directly on the routing configuration beforeEnterguard:

const router = new Router({
    
    
  routes: [
    {
    
    
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
    
    
		if (sessionStorage.getItem("token")) {
    
    
			next();
		} else {
    
    
			alert("请先登录");
			next("/login");
		}
      }
    }
  ]
})

These guards have the same method parameters as the global front guard.

Component internal guard

Used inside the component, and is equal to data, created, mounted, and methods

Use beforeRouteEnter as an example:

  beforeRouteEnter(to, from, next) {
    
    
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
    if (sessionStorage.getItem("token")) {
    
    
      next();
    } else {
    
    
      alert("请先登录");
      next("/login");
    }
  },

reference

Guess you like

Origin blog.csdn.net/weixin_45844049/article/details/115014366
Recommended