SoFunction
Updated on 2025-04-05

vue directive global custom instruction to implement button-level permission control operation method

In daily projects, it is usually necessary to judge the button operation permissions of the current user based on the data returned by the background interface. For the current logged-in user, this button is displayed only when the current button has the permission; if the current button does not have this permission, this button will not be displayed. For this scenario, it can beCustomize the global registration directive for button-level permission control.

concept

In addition to the default settings core instructions (v-modelandv-show ), vueAllows registration of custom directives, which can be used for ordinaryDOMThe element performs the underlying operation. This is an effective supplement and extension that can be used not only to define anydomoperation, and can be reused.

Register a custom instruction into:

1) Global registration

2) Local registration

Global custom commands

: Used to register globally or get global directives, which can write a custom event.

(el, hooks)

Parameter 1 (el): The name of the custom directive

Parameter 2 (hooks): hook function object for custom directive

Local custom commands

A local custom directive is an object, the attributes of the object are the name of the custom directive, and the value of the attributes in the object is the hook function object of the custom directive. as follows:

<template>
  <div></div>
</template>
<script>
export default {
  directives: {
    // The attribute name is a custom directive name    // The property value is a hook function object for custom directives    name: {
    }
  }
}
</script>

Custom commandsHook function and parameters of hook function

('permission', {
  bind: function (el, binding, vnode) {},
  inserted: function (el, binding, vnode) {},
  update: function (el, binding, vnode, oldVnode) {},
  componentUpdated: function (el, binding, vnode, oldVnode) {},
  unbind: function (el, binding, vnode) {}
})

Hook function

Custom instructions have five life cycles (also called hook functions), namely:bind,inserted,update,componentUpdated,unbind

  • bind: Called only once, and the instruction is called the first time it is bound to an element. This hook function can define an initialization setting that is executed once when binding. (bindWhen the parent node isnull,becausebindYesdomCalled before tree drawing)
  • inserted: Called when the bound element is inserted into the parent node (only guarantees that the parent node exists, but it may not be inserted into the document.domcall after the tree is drawn).
  • update: The template bound to the elementvNodeCalled when updated, but may occur in its childvNodeBefore update. The value of the instruction may have changed or not. You can ignore unnecessary template updates by comparing the binding values ​​before and after the update.
  • componentUpdated: The component where the bound element is locatedVNodeAnd its sonVNodeCalled after all updates.
  • unbind: Called only once, and is called when the instruction is unbined from the element. Hook function parameter description

Common parameters passed in custom directives:

  • el: The element bound to the instruction can be used to operate directlyDOM
  • binding: An object containing a lot of information about instructions. as follows:
  • name: Instruction name, not includingv-Prefix.
  • value: The binding value of the directive, for example:v-my-directive="1 + 1"The binding value is2
  • oldValue: The previous value bound to the instruction is onlyupdateandcomponentUpdatedAvailable in the hook. Available regardless of whether the value changes or not.
  • expression: Instruction expression in the form of a string. For examplev-my-directive="1 + 1"In, the expression is"1 + 1"
  • arg: Parameters passed to the instruction, optional. For examplev-my-directive:fooIn, the parameters are"foo"
  • modifiers: An object containing modifiers. For example:In, the modifier object is{ foo: true, bar: true }

vnode: Virtual node generated by Vue compilation.

oldVnode: The previous virtual node, onlyupdateandcomponentUpdatedAvailable in the hook.

Apart fromelIn addition, other parameters should be read-only.

Global custom command project application

Application scenario: Customize a permission command to judge the permissionsDomShow and hide.

The permission data structure returned by the backend interface is:

{"search":"search","create":"news","edit":"edit","enable":"top","forbidden":"untop","delete":"delete":"delete"}

Implementation principle:

existel-buttonSet the tag value on the button, usevueThe instruction function obtains the value of the tag bound to the button instance object and the button, and matches the button permission data obtained from the interface. If the match is successful, it proves that the user has the permission to use the button. If it is found that there is no permission to use, write code in the instruction processing function to remove the button, and the button will not be seen on the interface.

existsrcCreated in the directorydirectiveDirectory, create a new directory in the directorydocument:

const permission = {
	// Global registration custom directive  install (Vue) {
    // Use the inserted function to detect whether the bound element has permission when it is inserted into the parent node.    ('permission', {
      inserted (el, binding, vnode) {
		 /*el: The element bound to the instruction can be used to directly operate the DOM.
		      binding: An object that contains a lot of information about a directive.
		      vnode: Vue compiles the generated virtual node.  */
        const path = (1).split('?')[0]
        const { value } = binding
				// Customize the execution function of the command to get the button permission array in the login cache        const power = ()
        const operate = power[path] || {}
        if (!operate[value]) {
					// Determine whether you have permissions. If you do not have permissions, delete the node           && (el)
        }
      }
    })
  }
}
export default permission

In the entry filesrc\Introduce custom instructions:

import permissionfrom './directive/permission'
(permission)

In the page used, just quote in the buttonv-operateInstructions, assignment judgment:

<el-button @click='delHandle' type="primary" v-permission="'delete'">delete</el-button>

This is the article about the implementation of button-level permission control by vue directive global custom commands. For more related vue directive button-level permission control content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!