Vue custom instructions display hidden instructions according to permission control, global registration and local registration of custom instructions

  • Vue custom command shows and hides commands based on permission control
  • Vue custom instruction global registration and local registration
  • command lifecycle

Display hidden commands based on permission control

First, create a new power.js file under the ==src/directives/== folder:

let authList = ['save','edit',......] // 可访问的权限列表

const power = {
    
    
  // 指令的定义
  inserted: function (el, binding) {
    
    
    if (!binding.value) {
    
     return }
    let value = `${
      
      binding.value}`
    if (!authList.includes(value)) {
    
    
      el.parentNode && el.parentNode.removeChild(el)
    }
  }
}

export default power

Then introduce the directive where you want to use it:

import {power} from ‘@/directives/power.js’

Register the directive inside the component:

directives: { power },

computed: {…

Finally, bind the directive on the component code that needs to control the permission:

<el-button v-power="'save'" type="primary" plain @click="save">保存</el-button>

- Replenish:

If you want to register the command globally, you can use:

Vue.directive('focus', {
  	// el为dom元素
  	inserted: function (el) {
    	// 自动获取元素焦点
    	el.focus();
 	}
});

Custom directive life cycle:

  • bind: function (el, binding, vnode) { el.style['color'] = binding.value }, // only called once, when the instruction is bound to the element for the first time, use this hook to define a binding The initialization action is executed once.

  • inserted: function () {}, // Called when the bound element is inserted into the parent node (it can be called if the parent node exists, and does not need to exist in the document)
  • update: function () {}, // Called when the template where the binding and element are located is updated, and regardless of whether the binding value changes, by comparing the binding value before and after the update, unnecessary template updates are ignored
  • componentUpdated: function () {}, // Called when the template where the bound element is located completes an update update cycle
  • unbind: function () {} // only called once, when the instruction element is unbound

Guess you like

Origin blog.csdn.net/qq_35517283/article/details/129859215