In the Vue3 + TypeScript project, you can control the display and hiding of elements through custom instructions to implement permission management functions. This article will introduce in detail how to write av-permission
Directives to dynamically control the rendering of elements based on user permissions.
Functional Overview
v-permission
It is a custom directive with the following functions:
- Pass in a permission array, e.g.
['OrderList']
。 - Get a list of permissions that the user has from Vuex.
- If the user does not specify permissions, remove the corresponding element from the DOM.
- Support dynamic updates, through
updated
Hook recheck permissions.
Implementation steps
1. Create new directives/
On the projectdirectives
Created in the directory, the content is as follows:
import { App, DirectiveBinding } from 'vue'; import store from '@/store'; // Determine whether there is permissionconst hasPermission = (value: Array<string>, el: Element) => { // Check whether permission parameters are configured if (!(value) || === 0) { throw new Error(`v-permission Configuring permissions are required,For example v-permission="['xxx']"`); } // Get user permissions const ruleNames: Array<string> = ['menu/getRuleNames'] || []; if (!(ruleNames)) { ('The permission data "menu/getRuleNames" is incorrect in format, please check the store configuration. '); return; } // Determine whether there is permission const hasAuth = ((val) => (val)); if (!hasAuth && ) { (el); // Remove elements } return hasAuth; }; export default { install(app: App) { ('permission', { mounted(el: Element, binding: DirectiveBinding) { hasPermission(, el); }, updated(el: Element, binding: DirectiveBinding) { hasPermission(, el); }, }); }, };
Function description
-
mounted
hook: Check permissions when the element is mounted. If there is no permission, remove the element. -
updated
hook: Recheck permissions when an element or bound value is updated. - Error message: When the value passed in is incorrect, an error is thrown or a warning is given.
-
['menu/getRuleNames']
: Suppose you get the user permission list from Vuex and return an array of strings.
2. Introduce commands in
existRegister the directive in the file:
import { createApp } from 'vue'; import App from './'; import store from '@/store'; import permission from '@/directives/permission'; const app = createApp(App); (store); (permission); // Register custom commands('#app');
3. Usev-permission
Instructions
Use in templatesv-permission
Directive, pass in permission array:
<template> <div> <!-- User owned 'OrderList'Show when permissions are --> <button v-permission="['OrderList']">Permissions buttons</button> <!-- 仅管理员Show when permissions are --> <div v-permission="['admin']">Only content visible to administrators</div> </div> </template>
4. Permission data description
Assumptions['menu/getRuleNames']
Returns the following permission array:
['OrderList', 'admin', 'user:read']
- If passed in
['admin']
, the current user has this permission, and the element is displayed. - If passed in
['user:write']
, the current user does not have this permission, the element is removed
Complete process review
-
definition
permission
instruction: judge permissions and remove elements without permissions. -
Registration Instructions:exist
Register global instructions.
-
User command: Use in templates
v-permission
, pass in the required permission array. - Support dynamic updates: The permissions are rechecked when the element is updated.
Things to note
-
Configuration: Ensure that permission data is correctly configured in Vuex and returns an array format.
-
Transfer and verify:
v-permission
The bound value must be an array, otherwise an error will be thrown. -
Dynamic permission changes: If the permission list is updated dynamically, you need to ensure that the page is re-rendered or triggered.
updated
hook.
Summarize
passv-permission
Custom directives allow easy permission control in Vue3 projects, remove unauthorized elements, and improve user experience and project security. Depending on actual needs, this directive can be further expanded, such as implementing hidden elements instead of removing elements, supporting multiple permission logic, etc.
This is the article about how to customize v-permission permission directives in Vue3. For more related contents of v-permission instructions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!