I used to think the phrase “always believe that something good is going to happen” was so pretentious, but now I like this one full of confidence. “This child in the future, no matter what kind of put-downs, humiliations he encounters, say you can’t. This kid will be as confident as Luyu, really? I don’t believe it.” Ha, ha, ha.

Without further ado, this blog focuses on the front-end permission logic, which is restored to its essence in the simplest code possible. Vue-router Vuex sessionStorage is mainly used here. Effect:

The flow chart is as follows:

Login permissions

Data stored in sessionStorage will remain in the browser until we close the corresponding TAB page. SetItem (‘login’, “login”); sessionStorage.setitem (‘login’, “login”); Indicates that the user has logged in. Refresh the page according to whether there is login in sessionStorage to determine whether the user has logged in.

Vue Router

The Vue Router is used to manage our front-end routing. There are hash and history modes. This article introduces the principles and differences between the two routing modes.

  • The global navigation guard function is usedrouter.beforeEach((to, from, next)=>{})Perform permission routing logic judgment.
  • usingrouter.addRoutes(menus);Dynamically Adding routes
  • next(); And next ({… To}) are two different operations, although the addresses of both jumps are the same. next(); Yes Continue the current route. next({ … To}) terminates the current route and rejumps totoAddress to go to. Using next ({… To}) can waitrouter.addRoutes(menus);After adding a route, perform the redirect operation.

Divide the route into router.js and appRouter. Js files. Router. js stores routes that do not require permissions, including the login, home page, and notFound pages. Login and the home page are pages that can be accessed without permission. AppRouter. Js stores the list of routes that are dynamically added to the routing object after login. Path: ‘*’, redirect: ‘/notFound’ at the end of the appRouter. Js file. We put the routing processing logic in router.js.

//router.js
const whiteList = ['/login'.'/index'] 
router.beforeEach(async(to, from, next) => {
  // Determine whether to log in
  const hasLogin = sessionStorage.getItem('login')?true : false;
  document.title = to.meta.title;
  if(! hasLogin){if(whiteList.indexOf(to.path)! = = -1){
      next();
    }else{
      next({path: "/login"}); }}else{
    if(to.path==='/login') {// Log out
      sessionStorage.removeItem("login");
      sessionStorage.removeItem("menu");
      sessionStorage.removeItem("roles");
      sessionStorage.removeItem("curPath");
      next();
    }else{
      // Determine whether to refresh the page
      const hasRoles = store.state.user.roles && store.state.user.roles.length > 0;
      if(hasRoles){
        next();
      }else{
        // To regain the user's permissions (roles), see the Vuex section
        const roles = await store.dispatch('getRoles');
        const menus = await store.dispatch('getMenus'); router.addRoutes(menus); next({ ... to,replace: true}); }}}});Copy the code

Vuex

State is divided into user and menu modules as required. After login, we can get the role of the current user or the routing list of the current user from the back end.

Role information is stored in the User module. This information can be accessed in the router.js file to determine whether the page is refreshed. Once the page is refreshed, the Vuex memory information will be cleared. At this point, the role of the current user or the list of accessible routes should be retrieved from the back end. In this example, the role is directly set to admin. Do not place dynamic routing components in the approuter.js file.

Dynamic routes are stored in the Menu module after login. App. vue dynamically generates the corresponding route jump menu based on the information.

A Store. Dispatch operation returns a Promise object. The asynchronous operation is processed.

// user.js
const user = {
  state: {
    roles: []},mutations: {
    setRoles: (state, val) = >{
      state.roles.push(val);
      sessionStorage.setItem("roles", val); }},actions: {
    setRoles: (context, val) = >{
      context.commit("setRoles", val);
    },
    getRoles: (context) = >{
      return new Promise((resolve, reject) = >{
        // Impersonates the role or permissions of the current user on the request backend
        const roles = sessionStorage.getItem("roles");
        context.commit("setRoles", roles); resolve(); })}}}export default user;
Copy the code
//menu.js
import appRouter from '.. /.. /route/appRouter'
const menu = {
  state: {
    menuList: []},mutations: {
    setMenus: (state, menus) = > {
      state.menuList = menus;
      sessionStorage.setItem('menu'.JSON.stringify(menus)); }},actions: {
    getMenus: (context) = >{
      // The backend can be requested; Or filter the appRouter based on the data returned by the back end, using only authorized components.
      return new Promise((resolve, reject) = >{
        context.commit("setMenus", appRouter); resolve(appRouter); })}}}export default menu
Copy the code

The source code

Address: github.com/YY88Xu/vue-…

If there is any mistake or not precise place, please be sure to give correction, thank you very much. If you like or have some inspiration, welcome to like, to the author is also a kind of encouragement.