Vue3 custom directive
1. Create src/directives/file
//@ts-nocheck import { Directive } from "vue"; import { permission } from "@/directives/"; const allGlobalDirectives = { permission }; // (allGlobalDirectives, "allGlobalDirectives"); //Print discovery is the exported custom instruction name, permissionexport default { install(app) { (allGlobalDirectives).forEach(key => { //() returns an array, the value is the key names of all traversable properties (key, (allGlobalDirectives as { [key: string]: Directive })[key]); //key is the name of the custom instruction; the value of the custom instruction should be followed by the value, and the value type is string }); } };
2. Create src/directives/file
import type { DirectiveBinding } from 'vue' export const permission = (el: HTMLElement, binding: DirectiveBinding) => { // value Get the content bound by the user using custom directives const {value} = binding; // Get all permissions from the user // const permissionBtn = ("permission"); const permissionBtn = ["user.add23"]; // Determine whether the user uses custom instructions correctly if (value && value instanceof Array && > 0) { const permissionFunc = value; //Judge whether the user has the permissions of the buttons passed in and whether the user has the permissions of the buttons. //(), there is a result in the array that true returns true, and the remaining elements will not be detected again const hasPermission = ((role: any) => { return (role); }); ("hasPermission", value, hasPermission); // When the user does not have this button permission, set to hide this button if (!hasPermission) { = "none"; } } else { throw new Error("need roles! Like v-permission=\"['admin','editor']\""); } };
Introduced
// Introduce custom plug-in objects: register global componentsimport globalDirectives from "@/directives/"; const app = createApp(App); // Install custom commands(globalDirectives); ("#app");
4. Use on the page
<span v-permission="['']" class="padding-right-20">test</span>
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.