Vue--Router -- hook function (navigation guard) -- usage scenario / instance

Original website:

brief introduction

explain

This article introduces the usage scenario of the hook function (navigation guard) of Vue Router.

Navigation guard usage of Vue Router, Official website It is described in great detail in. Only the usage scenarios are introduced here.

Official website

Navigation guard | Vue Router

Hook function type

Global hook function

beforeEach(): the function executed before each route entry.
After each (): the function executed after each route entry.
beforeResolve(): new in 2.5

Hook function of a single route

beforeEnter()

Routing hook function in component

beforeRouteEnter()
beforeRouteLeave()
beforeRouteUpdate()

Navigation execution process

  1. Navigation is triggered.
  2. Call beforeroutleave guard in the deactivated component.
  3. Call the global beforeEach guard.
  4. Call beforeRouteUpdate guard (2.2 +) in the reused component.
  5. Call beforeEnter in the routing configuration.
  6. Resolve asynchronous routing components.
  7. Call beforeRouteEnter in the activated component.
  8. Call the global beforeResolve guard (2.5 +).
  9. Navigation confirmed.
  10. Call the global afterEach hook.
  11. Trigger DOM update.
  12. Call the callback function passed to next in beforeRouteEnter, and the created component instance will be passed in as the parameter of the callback function.

Usage scenario

Global hook

beforeEach

The global front navigation guard is executed before loading the page.

Application scenario

  1. Page Jump pre-processing. For example: intercept the page that needs to log in and jump to the login page
  2. Login judgment, administrator permission judgment and browser judgment on the entry page

Sample code

// Written in the js file of the route
router.beforeEach((to, from, next) => {
    const role = localStorage.getItem('ms_username');
    if(!role && to.path !== '/login'){
        next('/login');
    }else if(to.meta.permission){
        // If you have administrator privileges, you can enter. Here is just a simple simulation of administrator privileges
        role === 'admin' ? next() : next('/403');
    }else{
        // Simply judge that IE10 and below do not enter the rich text editor, and this component is incompatible
        if(navigator.userAgent.indexOf('MSIE') > -1 && to.path === '/editor'){
            Vue.prototype.$alert(
            	'vue-quill-editor Incompatible components IE10 And the following browsers, please use a higher version of the browser to view', 
            	'Browser incompatibility notification', 
            	{confirmButtonText: 'determine'}
            );
        }else{
            next();
        }
    }
})

Single route hook

beforeEnter

Execute before entering a route.

Application scenario

  1. Spell the parameters passed from the previous component to the back of the new route

Sample code

// Written in a route of js in the route file
const routes = [
  {
    path: '/',
    beforeEnter: (to, from, next) => {
      const href = window.location.href
      const queryString = href.slice(href.indexOf('?'))
      // Before jumping to a route, splice the parameters of the previous route behind the route to be redirected
      // Can be used to initialize page data
      next({ path: `/home/dashboard${queryString}`, replace: true })
    }
  },
  
 // ...
  
]

Hook in assembly

Application scenario 1: clear the timer in the current component

When there is a timer in a component, you can use beforeroutleave to clear the timer when switching routes to avoid occupying memory.

beforeRouteLeave (to, from, next) {  
 	window.clearInterval(this.timer) //Clear timer   
 	next()
}

Application scenario 2: when there is an unclosed window or unsaved content in the page, the page Jump is prevented

If there is important information in the page that needs to be saved before the user can jump, or there is a pop-up box, the user should be prevented from jumping, combined with vuex state management (whether dialogVisibility is saved)

beforeRouteLeave (to, from, next) {
	 //Determine whether the status of the pop-up box and whether to save information
	 if (this.dialogVisibility === true) {
	    this.dialogVisibility = false //Close pop ups
	    next(false)                   //Return to the current page and prevent page Jump
	  }else if(this.saveMessage === false) {
	    alert('Please save the information and exit!') //pop-up warning 
	    next(false)              //Return to the current page and prevent page Jump
	  }else {
	    next() //Otherwise, jump is allowed
	  }
 }

Application scenario 3: save relevant contents to Vuex or Session

When users need to close the page, they can save the public information to session or Vuex

 beforeRouteLeave (to, from, next) {
    localStorage.setItem(name, content); //Save to localStorage
    next()
}

Writing method

Requirement: determine whether login is required by judging the meta attribute auth of login status

Writing method 1: used at the Router definition

router/index.js

import Vue from 'vue'
import Router from 'vue-router'

const vueRouter = new Router({
    routes: [
    	{
		 path: '/login',
          name: 'login',
          component: login,
		},
        {
          path: '/index',
          name: 'index',
          component: index,
          meta:{auth:true,keepAlive: false},
          children: [
            {name: 'children1', path: 'children1', component: children1},
            {name: 'children2', path: 'children2', component: children2}
          ]
        }
    ]
});

vueRouter.beforeEach(function (to, from, next) {
    const nextRoute = [ 'index', 'children1', 'children2'];
        // const auth = store.state.auth; // Save status in vueX
        const auth = meta.auth;
    //Jump to the above three pages
    if (nextRoute.indexOf(to.name) >= 0) {
        //Not logged in
        if (!auth.IsLogin) {
            vueRouter.push({name: 'login'})
        }
    }
    //If you have logged in, go to the login page and jump to the home page
    if (to.name === 'login') {
        if (auth.IsLogin) {
            vueRouter.push({name: 'index'});
        }
    }
    next();
});

Writing 2: in main Insert in JS

router/index.js

import Vue from 'vue'
import Router from 'vue-router'

const vueRouter = new Router({
    routes: [
    	{
		 path: '/login',
          name: 'login',
          component: login,
		},
        {
          path: '/index',
          name: 'index',
          component: index,
          meta:{auth:true,keepAlive: false},
          children: [
            {name: 'children1', path: 'children1', component: children1},
            {name: 'children2', path: 'children2', component: children2}
          ]
        }
    ]
});
export default vueRouter;

main.js

import vueRouter from './router'
vueRouter.beforeEach(function (to, from, next) {
    const nextRoute = [ 'index', 'children1', 'children2'];
        // const auth = store.state.auth; // Save status in vueX
        const auth = meta.auth;
    //Jump to the above three pages
    if (nextRoute.indexOf(to.name) >= 0) {
        //Not logged in
        if (!auth.IsLogin) {
            vueRouter.push({name: 'login'})
        }
    }
    //If you have logged in, go to the login page and jump to the home page
    if (to.name === 'login') {
        if (auth.IsLogin) {
            vueRouter.push({name: 'index'});
        }
    }
    next();
});

 

Keywords: Javascript Front-end Vue Vue.js

Added by adamgram on Tue, 01 Feb 2022 07:35:28 +0200