SoFunction
Updated on 2025-03-03

Two methods of Vue permission control (routing verification)

The following are two methods of permission control:

  • Routing meta information (meta)
  • Dynamic load menus and routes (addRoutes)

Routing meta information (meta)

If a website has different roles, such as administrators and ordinary users, the pages that require different roles to access are different.

At this time, we can put all pages in the routing table, just judge the role permissions when accessing. If you have permission, you will be allowed to access. If you don't have permission, you will be denied access and jump to page 404

vue-router provides meta-information meta configuration interface when building routes. We can add the corresponding permissions for the route in the meta-information, and then check the relevant permissions in the route guard to control its route jump.

The roles that can access the route can be added to roles in the meta attribute of each route. After each login, the user returns the user's role. Then when accessing the page, compare the meta attribute of the route with the user's role. If the user's role is in the routed roles, it is accessible, and if it is not there, access will be denied.

Code Example 1:

Routing information:

routes: [
  {
    path: '/login',
    name: 'login',
    meta: {
      roles: ['admin', 'user']
    },
    component: () => import('../components/')
  },
  {
    path: 'home',
    name: 'home',
    meta: {
      roles: ['admin']
    },
    component: () => import('../views/')
  },
]

Page control:

//Suppose there are two roles: admin and user//User role obtained from the backgroundconst role = 'user'
// When entering a page, the navigation guard event will be triggered.((to,from,next)=>{
 if((role)){
 next() //Released }esle{
 next({path:"/404"}) //Skip to page 404 }
})

Code Example 2

Of course, one of the following methods can also be used:

// 
// Routing table meta information[
 {
  path: '',
  redirect: '/home'
 },
 {
  path: '/home',
  meta: {
   title: 'Home',
   icon: 'home'
  }
 },
 {
  path: '/userCenter',
  meta: {
   title: 'Personal Center',
   requireAuth: true // Add the permission identifier for the response in the meta of the route that needs to be logged in  }
 }
]

// Access Meta Information in Guardfunction gaurd (to, from, next) {
 // (record => )
 // Can be found here}

This permission identifier can be added under multiple routes to achieve the control purpose

As long as you change the page, you need to see if this permission is available, so you can configure it in the largest route

Store information

Generally, after logging in, the user will store the user's authentication information locally. You can use token, cookies, etc., here we use token.

Save the user's token into localStorage, and the user information is stored in the memory store. This can store an attribute auth that marks the user's login status in vuex, which facilitates permission control.

Code Example

// 
{
 state: {
  token: ('token'),
  auth: false,
  userInfo: {}
 },
 mutations: {
  setToken (state, token) {
    = token
   ('token', token)
  },
  clearToken (state) {
    = ''
   ('token', '')
  },
  setUserInfo (state, userInfo) {
    = userInfo
    = true // Mark auth as true when obtaining user information. Of course, you can directly judge userInfo  }
 },
 actions: {
  async getUserInfo (ctx, token) {
   return fetchUserInfo(token).then(response => {
    if ( === 200) {
     ('setUserInfo', )
    }
    return response
   })
  },
  async login (ctx, account) {
   return login(account).then(response => {
    if ( === 200) {
     ('setUserInfo', )
     ('setToken', )
    }
   })
  }
 }
}

After writing the routing table and vuex, set a global guard for all routes, perform permission checks before entering the route, and navigate to the corresponding route.

// 
{
 state: {
  token: ('token'),
  auth: false,
  userInfo: {}
 },
 mutations: {
  setToken (state, token) {
    = token
   ('token', token)
  },
  clearToken (state) {
    = ''
   ('token', '')
  },
  setUserInfo (state, userInfo) {
    = userInfo
    = true // Mark auth as true when obtaining user information. Of course, you can directly judge userInfo  }
 },
 actions: {
  async getUserInfo (ctx, token) {
   return fetchUserInfo(token).then(response => {
    if ( === 200) {
     ('setUserInfo', )
    }
    return response
   })
  },
  async login (ctx, account) {
   return login(account).then(response => {
    if ( === 200) {
     ('setUserInfo', )
     ('setToken', )
    }
   })
  }
 }
}

The above method is based on the jwt authentication method. The local user information is not persisted, and only the token is saved. When the user refreshes or reopens the web page, he will try to request user information when entering the page that needs to be logged in. This operation is only performed once during the entire access process until it is refreshed or reopened. It is very good for later development, maintenance and expansion support for the application.

Dynamic load menus and routes (addRoutes)

Sometimes, for security, we need to dynamically add menus and routing tables based on user permissions or user attributes, so that users can customize their functions. vue-router provides the addRoutes() method, which can dynamically register routes. It should be noted that dynamically adding routes is pushed routes in the routing table. Since routes match in order, routes such as 404 pages need to be placed at the end of dynamic addition.

Code Example

// 
// Extract routes that require dynamic registration into vuexconst dynamicRoutes = [
 {
  path: '/manage',
  name: 'Manage',
  meta: {
   requireAuth: true
  },
  component: () => import('./views/Manage')
 },
 {
  path: '/userCenter',
  name: 'UserCenter',
  meta: {
   requireAuth: true
  },
  component: () => import('./views/UserCenter')
 }
]

Add a userRoutes array in vuex to store user custom menus. Generate the user's routing table in setUserInfo based on the menu returned by the backend.

// 
setUserInfo (state, userInfo) {
  = userInfo
  = true // Mark auth as true when obtaining user information. Of course, you can directly judge userInfo // Generate user routing table  = (route => {
  return (menu =>  === )
 })
 () // Register a route}

Modify menu rendering

// 
<div >
 <router-link to="/">Home page</router-link>
 <router-link to="/login">Log in</router-link>
 <template v-for="(menu, index) of $">
  <router-link :to="{ name:  }" :key="index">{{}}</router-link>
 </template>
</div>

Summarize

The above are the two methods of Vue permission control introduced to you (routing verification). I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!