SoFunction
Updated on 2025-04-04

One article will help you understand the permission control in Vue project

Menu permission control

In Vue, menus need to be generated dynamically based on user's permission information and permission verification is performed at the routing level to realize menu routing permission control. You can follow the following steps:

1. Define menu data structure

First, define a menu data structure, including information such as the name, path, and permission identification of the menu item. You can store menu data in an array or object according to project needs.

const menuData = [
    {
    name: 'Home',
    path: '/home',
    permission: 'home:view' // Permission ID    },
    {
    name: 'Products',
    path: '/products',
    permission: 'products:view'
    },
    {
    name: 'Orders',
    path: '/orders',
    permission: 'orders:view'
    },
    // Other menu items...    ];

2. Obtain user permissions

When a user logs in or initializes the application, obtain the permission information of the current user and save it locally, for example using Vuex or localStorage. Here is a sample code implementation:

 // In the processing logic after login is successful // Assume that the user permission information obtained from the server is userPermissions //Storage to Vuex this.$('setUserPermissions', userPermissions); 
 // Or store to localStorage ('userPermissions', (userPermissions));

In the above code, it is assumed that the user's permission information is obtained from the server side.userPermissions. You can use VuexcommitMethod to trigger a mutation to store permission information in Vuex's state management. Alternatively, you can pass the permission information throughlocalStorageofsetItemMethods are stored in local storage and usually need to be converted to string format.

Sample code for storing user permissions in Vuex is as follows:

// Define mutations and state in Vuex store module//  
import Vue from 'vue'; 
import Vuex from 'vuex'; 
(Vuex); 
const store = new ({ 
    state: { 
        userPermissions: [] // The initial state is an empty array    },
    mutations: { 
        setUserPermissions(state, permissions) 
            { 
                 = permissions; 
            } 
        } 
       }); 
 export default store;

In the above example, we define a name calleduserPermissionsand in the state ofsetUserPermissionsThe incoming permission information is assigned to this state in mutation.

uselocalStorageThe example code for storing user permissions is as follows:

 // In the processing logic after login is successful // Assume that the user permission information obtained from the server is userPermissions ('userPermissions', (userPermissions));

In the above code, we uselocalStorageofsetItemMethod stores user permission information as a string. In this way, permission information will be saved in the browser's local storage.

3. Generate menus based on permissions

In the menu component, the menu data is traversed based on the user's permission information, and corresponding accessible menu items are generated based on the permission identification owned by the user. You can use Vue's conditional rendering instructions, such asv-iforv-show, to dynamically display or hide menu items according to user's permissions. Here is a sample code implementation:

<template> 
    <div> 
        <ul> 
            <li v-for="item in menuData" :key="" v-show="hasPermission()"> 
            <router-link :to="">{{  }}</router-link> 
            </li> 
         </ul> 
     </div> 
 </template> 
 <script> 
     export default { 
         computed: { 
             menuData() { 
                 // Get menu data                 return menuData; 
             } }, 
         methods: { 
             hasPermission(permission) 
                 { 
                     // Determine whether the user has permission                     // Assume that permission information is stored in this.$                     const userPermissions = this.$; 
                     return (permission); 
                 } 
          } 
     } 
</script>

Router Guard Permission Control

In Vue Router, configure routing based on user permission information. In the routing configuration, set the corresponding permission identifier for each route that requires permission control. In Navigation Guards, permissions are verified for user access. Decide whether to allow users to access the route based on the user's permission information and routing configuration.

  • Global front guard (beforeEach): In the global front guard, permission verification is performed based on the current route's permission identification and user's permission information. If the user does not have permission to access the current route, you can redirect to the login page or display a message without permission.
  • Routing level meta information (meta): In routing configuration, the meta information (meta) field is used to store the permission identifier of the route. Permission verification and control are performed by obtaining the meta information of the route in the navigation guard.

Vue Router configuration: Configure the routing of Vue Router according to the permission identification of menu data, and perform permission verification in the navigation guard.

import Vue from 'vue'; 
import Router from 'vue-router'; 
(Router); 
const router = new Router({ 
    routes: [ 
        { 
            path: '/home', 
            component: Home, 
            meta: { permission: 'home:view' } //Routing permission identification        }, 
        { 
             path: '/products', 
             component: Products, 
             meta: { permission: 'products:view' } 
         }, 
         { 
             path: '/orders', 
             component: Orders, 
             meta: { permission: 'orders:view' } 
          }, 
          // Other routing configurations...       ] 
 }); 
 ((to, from, next) => { 
     const userPermissions = ; 
     const requiredPermission = ; 
         if (requiredPermission && !(requiredPermission)) { 
             // No permissions, redirect to the login page or display a no permission prompt             next('/login');
             // Or display the unauthorized prompt page             // next('/no-permission'); 
          } else { 
              next(); 
           } 
    });
export default router;

Authorization control of the build-level button

In the Vue component that requires button-level permission control, instructions or calculation properties can be used to determine whether the user has corresponding permissions, thereby determining whether the button is displayed or operable.

Use custom directives:

<template> 
    <button v-permission="'user:create'">Create User</button> </template> <script> 
export default { 
    directives: { 
        permission: { 
            inserted(el, binding) 
                { 
                    const userPermissions = this.$; 
                    const requiredPermission = ; 
                    if (!(requiredPermission)) { 
                           = 'none'; // Or disable buttons and other operations                     } 
                } 
            } 
         } 
     } 
 </script>

Use computed properties:

<template> 
       <button v-if="hasPermission('user:create')">Create User</button> </template> 
<script> 
        export default { 
            methods: { 
                hasPermission(permission) { 
                    const userPermissions = this.$; 
                    return (permission); 
             } 
        } 
     } 
</script>

In the above example, we used a custom directivev-permissionand calculate propertieshasPermissionTo determine whether the user hasuser:createpermissions. If the user does not have this permission, the button will be hidden or disabled.

It should be noted that in the above example, we assume that the user's permission information is stored in VuexYou can make corresponding adjustments according to the actual situation.

API permission management

Sometimes it is necessary to restrict users' access to the backend API based on the user's permission information. You can make permission judgments before the front-end sends the API request, and decide whether to send the request or perform other processing based on the permission information. The sample code is as follows:

((config) =&gt; { 
    // Determine whether the user has permission to access the API    if (!hasPermission()) { 
        // Access is not allowed, request is cancelled or other processing methods        return (new Error('No permission to access this API')); 
   } 
   return config; 
   }, 
   (error) =&gt; { 
    return (error); 
   });

Dynamic routing permissions

In some cases, permissions may dynamically generate routes based on user roles. This can be achieved by dynamically generating routing configurations based on user permission information when logging in or permission updates. For example, you can map permission information into routing objects and then add these dynamically generated routing configurations to the router. The sample code is as follows:

// Dynamically generate routing configuration    function generateRoutes(permissionList) { 
        const routes = []; 
        (permission =&gt; { 
            const route = { 
                path: , 
                component: () =&gt; import(`@/views/${}`), 
                meta: { // Other routing meta information } };                (route); 
            }); 
        return routes; 
      } 
      // Add dynamic routing      (generateRoutes(permissionList));

Role Management

Sometimes permissions need to be managed based on the user's role. Each role can be assigned a set of permissions and determine whether the user has permission to access a specific function based on the role to which he or she belongs. This can be processed by obtaining the user's role information after the user logs in and processing it according to the role when permission judgment is required. The sample code is as follows:

1. Define roles and permissions:

   // Role list   const roles = [ 
       { id: 1, name: 'administrator' }, 
       { id: 2, name: 'Ordinary User' } 
   ]; 
   // Permission list   const permissions = [ 
       { id: 1, name: 'Create a user', role: 'administrator' }, 
       { id: 2, name: 'Edit user', role: 'administrator' }, 
       { id: 3, name: 'View User', role: 'administrator' }, 
       { id: 4, name: 'View User List', role: 'Ordinary User' } 
   ];

2. Obtain user role:

    function getUserRoles(userId) { 
        // Obtain the role list to which the user belongs according to the user ID        // Return an array containing role names   }

3. Permission judgment:

   function hasPermission(permission, userId) 
   { 
       const userRoles = getUserRoles(userId); 
       //Judge whether you have permission based on the user role       return (p =&gt;  === permission &amp;&amp; ()); 
    }

In this example, we define the role list and the permission list. passgetUserRoles()Functions get the user's role list and usehasPermission()Function to determine whether the user has specific permissions.hasPermission()The function will check whether the user role contains the corresponding permissions, and if it is included, it will returntrue, otherwise returnfalse

The above are the permission-related scenarios, solutions and code examples compiled in actual applications. The example is just a simple demonstration. In actual situations, more complex roles and permission management solutions may be required.

The above is a detailed article that will help you understand the permission control in Vue project. For more information about permission control in Vue project, please follow my other related articles!