SoFunction
Updated on 2025-04-12

A brief analysis of the implementation of permission management in Vue

Preface

In front-end development, permission management is a crucial task. Whether it is an enterprise-level application or a public platform, we need to ensure that users can only access and operate the content they are allowed. Provides flexible and powerful support when managing permissions. This tutorial will explore in-depth how to implement permission management in a project and explain in detail how to implement fine-grained control to the button level.

What is permission management

Permission management includes controlling which pages users can access, which data they view, what actions they perform, etc. Through permission management, we can ensure the security of the system and avoid unnecessary risks.

Implementation ideas

Permission management in .

Define roles and permissions: Define which roles are in the system (such as administrators, ordinary users) and which permissions each role has.

Store user permission information: When the user logs in, store user permission information on the front end (such as Vuex or Local Storage).

Global Router Guard: Set up global guards in Vue Router to monitor navigation behavior and perform permission verification.

Component-level permission processing: In specific components, display or hide specific content based on permissions.

Implementation steps

1. Define roles and permissions

First, we need to define which roles are in the system and the permissions for each role. A simple example could be:

const roles = {
  admin: {
    permissions: ['viewPage', 'editPage', 'deletePage', 'viewButton', 'editButton']
  },
  user: {
    permissions: ['viewPage', 'viewButton']
  }
};

2. Store user permission information

Usually, we get the user's permission information when the user logs in and store it in Vuex.

// 
import Vue from 'vue';
import Vuex from 'vuex';

(Vuex);

export default new ({
  state: {
    userPermissions: []
  },
  mutations: {
    setUserPermissions(state, permissions) {
       = permissions;
    }
  },
  actions: {
    fetchUserPermissions({ commit }, role) {
      commit('setUserPermissions', roles[role].permissions);
    }
  }
});

3. Global Routing Guard

To prevent users from accessing unauthorized pages, we can set up global guards in Vue Router.

// 
import Vue from 'vue';
import Router from 'vue-router';
import store from './store';

(Router);

const router = new Router({
  routes: [
    { path: '/view', component: ViewPage, meta: { permission: 'viewPage' } },
    { path: '/edit', component: EditPage, meta: { permission: 'editPage' } },
    // More routes...  ]
});

((to, from, next) => {
  const userPermissions = ;
  const requiredPermission = ;

  if (!requiredPermission || (requiredPermission)) {
    next();
  } else {
    next('/unauthorized'); // Redirect to unauthorized page  }
});

export default router;

4. Component-level permission processing

In specific components, we can display or hide specific content, such as buttons, based on permissions.

<template>
  <div>
    <button v-if="canEdit" @click="edit">Edit</button>
    <button v-if="canDelete" @click="delete">Delete</button>
  </div>
</template>

<script>
import { mapState } from 'vuex';

export default {
  computed: {
    ...mapState(['userPermissions']),
    canEdit() {
      return ('editButton');
    },
    canDelete() {
      return ('deleteButton');
    }
  },
  methods: {
    edit() {
      // Editing Logic    },
    delete() {
      // Delete logic    }
  }
};
</script>

Advanced Tips

1. Dynamic permission loading

In some complex applications, user permissions may change over time or need to be loaded from the server in real time. In this case, we can dynamically load permission information when the user logs in or every time the page is accessed.

// Obtain user permissions from the server after login or when component is mountedmethods: {
  async fetchPermissions() {
    try {
      const response = await ('/api/user/permissions');
      this.$('setUserPermissions', );
    } catch (error) {
      ('Failed to fetch permissions:', error);
    }
  }
},
created() {
  ();
}

2. Permission command

To more elegantly control the display and hiding of elements, we can create custom instructions.

// Permission command fileimport Vue from 'vue';
import store from './store';

('permission', {
  inserted(el, binding) {
    const { value } = binding;
    const userPermissions = ;

    if (!(value)) {
       && (el);
    }
  }
});

Use the following in the component:

<template>
  <div>
    <button v-permission="'editButton'" @click="edit">Edit</button>
    <button v-permission="'deleteButton'" @click="delete">Delete</button>
  </div>
</template>

This approach is not only concise, but also more readable.

3. Optimization of routing permission management

To manage routing permissions more flexibly, you can consider generating routing tables based on roles. This ensures that users will only see pages they have permission to access, avoiding unnecessary jumps and redirects.

// Generate routing table based on roleconst generateRoutes = (permissions) =&gt; {
  const allRoutes = [
    { path: '/view', component: ViewPage, meta: { permission: 'viewPage' } },
    { path: '/edit', component: EditPage, meta: { permission: 'editPage' } },
    // More routes...  ];

  return (route =&gt; ! || ());
};

// After the user logs in, dynamically load the route according to user permissions('fetchUserPermissions', userRole).then(() =&gt; {
  const userPermissions = ;
  const routes = generateRoutes(userPermissions);
  (routes);
});

4. Permission cache and refresh

To improve user experience and reduce server pressure, permission information can be cached locally (such as Local Storage) and refreshed when appropriate.

// Implement permission cache in Vuexexport default new ({
  state: {
    userPermissions: (('userPermissions')) || []
  },
  mutations: {
    setUserPermissions(state, permissions) {
       = permissions;
      ('userPermissions', (permissions));
    }
  },
  actions: {
    async fetchUserPermissions({ commit }) {
      try {
        const response = await ('/api/user/permissions');
        commit('setUserPermissions', );
      } catch (error) {
        ('Failed to fetch permissions:', error);
      }
    }
  }
});

5. Fine-grained permission control

In actual projects, we may need more fine-grained permission controls, such as access permissions for different data fields. This can be achieved through field-level permission definition and checking.

// Example: Check field permissions in component&lt;template&gt;
  &lt;div&gt;
    &lt;div v-if="userCanView('field1')"&gt;{{ data.field1 }}&lt;/div&gt;
    &lt;div v-if="userCanView('field2')"&gt;{{ data.field2 }}&lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  methods: {
    userCanView(field) {
      const fieldPermissions = {
        field1: 'viewField1',
        field2: 'viewField2'
      };
      return this.$(fieldPermissions[field]);
    }
  }
};
&lt;/script&gt;

Summarize

Through the above introduction, we not only mastered the methods of implementing basic permission management in , but also explored some advanced techniques and optimization strategies to make permission management more flexible and efficient. From page access control to button-level permissions to dynamic permission loading and cache management, these methods provide developers with a complete set of practical permission management solutions.

In actual development, the requirements for permission management may be more complex and changeable. We need to flexibly adjust and expand these methods according to specific project requirements to ensure the security and maintainability of the system.

The above is a detailed analysis of the implementation of permission management in Vue. For more information about Vue permission management, please follow my other related articles!