SoFunction
Updated on 2025-04-07

vue-router dynamic routing implements front-end permission management method

vue-router dynamic routing implements front-end permission management

I went out to interview two companies with a try-through mentality;

During the interview, one of the companies asked many questions about the implementation of permission management of the dynamic routing of vue-router;

After I came back, I studied it carefully

Dynamic routing is implemented based on the new method added by vue-router;

That is to achieve the permissions used by the user to determine which pages on the front end can be displayed and which cannot be displayed after logging in;

first step

Create vue-router

router/content

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import demo from '@/components/role'
import  notFind from '@/components/404'
(Router);
//Route without permissionsexport const constantRouterMap = [
  {
    path: '/',
    component: HelloWorld,
    name: 'front page'
  }, {
    path : '/404',
   component:notFind,
    meta : {
      title : '404 not found',
    }
  }
]
// When instantiating vue, only constantRouter is mountedexport default new Router({
  routes: constantRouterMap
});

//Asynchronous mount routing//Dynamic routing tables that need to be loaded according to permissionsexport const asyncRouterMap = [
  {
    path: '/role',
    component: demo,
    name: 'Permission Test',
    meta: { role: ['admin','super_editor'] }, //Permissions required by the page  },{
    path : '*',
    redirect : '/404'
  }
];

Step 2

Determine user permissions and add routes in the entry function

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in  with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import { asyncRouterMap, constantRouterMap } from './router';
import Vuex from "Vuex"
import VueDND from 'awe-dnd'
import BaiduMap from 'vue-baidu-map'
(Vuex)
function hasPermission(roles, route) {
  if ( && ) {
    (roles);
    return (role => (role) >= 0)
  } else {
    return true
  }
}
const store = new ({
  state: {
    count: 0,
    token:"asdsd",
    roles:"",
    routers:[],
    addRouters:[]
  },
  getters:{
    token(){
      return "asdsd"
    },
    roles(state ){
      return 
    },
    addRouters(state){
      return 
    },
    routers(state){
      return 
    }
  },
  actions:{
    GetInfo({state}){
      return {
        data:{
          role:=["admin"]
        }
      }
    },
    GenerateRoutes({ commit }, data){
      return new Promise(resolve => {
        const { roles } = data;
        (asyncRouterMap,roles);
        const accessedRouters = (v => {
          if (('admin') >= 0) return true;
          if (hasPermission(roles, v)) {
            if ( &&  > 0) {
               = (child => {
                if (hasPermission(roles, child)) {
                  return child
                }
                return false;
              });
              return v
            } else {
              return v
            }
          }
          return false;
        });
        (accessedRouters);
        commit('SET_ROUTERS', accessedRouters);
        resolve();
      })
    }
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      (routers);
       = routers;
       = (routers);
    }
  }
});
((to, from, next) => {
  if () { // Determine whether there is a token    if ( === '/login') {
      next({ path: '/' });
    } else {
      if ( === 0) { // Determine whether the current user has pulled the user_info information        ('GetInfo').then(res => { // Pull info          const roles = ;
          ('GenerateRoutes', { roles }).then(() => { // Generate accessible routing tables            ();
            () // Dynamically add accessible routing tables            next({ ...to, replace: true }) // hack method Make sure addRoutes is completed, set the replace: true so the navigation will not leave a history record          })
        }).catch(err => {
          (err);
        });
      } else {
        next() //When you have user permissions, it means that all accessable routes have been generated. If you access the full range of page 404 without permissions will be automatically entered.      }
    }
  } else {
    next('/login'); // Otherwise, all will be redirected to the login page  }
});

In this way, even if the user permissions are insufficient, you will not see the static resources of those pages; instead, you will directly display the 404 page you edited.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.