Vue custom v-has instruction to implement button permission judgment

Vue custom v-has instruction to implement button permission judgment

Application Scenario

Taking the background management system as an example, each user has different button permissions. After the administrator configures permissions, when the user logs in, he or she gets the button permission list from the interface, and then determines which buttons to display based on the background data.

Simply put, custom instructions

Vue.js official website's explanation of custom instructions

cn.vuejs.org/v2/guide/cu…

Basic Concepts

In addition to the default built-in instructions (v-model and v-show) for core functions, Vue can also register custom instructions.

In Vue 2.0, the main form of code reuse and abstraction is components. But in some cases, it is still necessary to perform low-level operations on ordinary DOM elements, and custom instructions will be used at this time.

For example, customize a v-focus directive, when the page loads, the input box will get the focus

<input v-focus>

Global Customization

// Register a global custom directive `v-focus`
Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted: function (el) {
    // Focus element el.focus()
  }
})

Local customization

//If you want to register a local directive, the component also accepts a directives option:
directives: {
  focus:
    // Definition of instruction inserted: function (el) {
      el.focus()
    }
  }
}

Hook function

A directive definition object can provide the following hook functions (all optional):

bind

Called only once, when the directive is first bound to an element. Here you can perform a one-time initialization setup.

inserted

Called when the bound element is inserted into the parent node (the parent node is only guaranteed to exist, but not necessarily inserted into the document)

update

Called when the VNode of the component is updated, but it may happen before its child VNodes are updated. The value of the instruction may or may not have changed. But you can ignore unnecessary template updates by comparing the values ​​before and after the update.

componentUpdated

Called after the VNode of the component where the instruction is located and its child VNodes are all updated.

unbind

Called only once, when the directive is unbound from the element.

other

In addition, there are some basic concepts, hook function parameters, dynamic instruction parameters, etc.

cn.vuejs.org/v2/guide/cu…

The official website explains it very clearly, so I won’t go into details here.

principle

If you are interested in the source code of custom instructions, there is also an article in Blog Park that explains it very clearly.

https://www.jb51.net/article/209716.htm

The principle is:

  • When parsing Vue's attributes, traverse each attribute;
  • Add a directives attribute to the object to save the instruction information;
  • After rendering is completed, the create hook function of the directives module will be executed;
  • The virtual node generated by Vue compilation, that is, after VNode is inserted into the parent node,
  • Execute each function in turn, and execute our custom defined inserted hook function

Custom directive v-has

Let’s get back to the topic.

Today we will mainly summarize: custom instruction v-has, button permission judgment

The login interface obtains the button permission list and stores it in the local cache LOGIN_USER_BUTTON_AUTH

The data format is as follows:

[
    {
        "checked":false,
        "component":"",
        "createTime":"2019-06-29 18:21:06",
        "createUser":"026a564bbfd84861ac4b65393644beef",
        "icon":"",
        "id":"1503273153861066776",
        "name":"Today's collection (case file)",
        "open":"true",
        "parentId":"2328050996633395469",
        "parentName":"Home",
        "permission":"sys:index:vol",
        "sort":103,
        "status":"0",
        "type":"2",
        "updateTime":"2021-01-27 15:51:15",
        "updateUser":"026a564bbfd84861ac4b65393644beef",
        "url":""
    }
]

Customizing the configuration of the v-has directive

In the utils folder, create a hasPermission.js file and export it uniformly in index.js

const hasPermission = {
    install (Vue, options) {
        Vue.directive('has', {
            inserted: (el, binding, vnode)=>{
                filterGlobalPermission(el, binding, vnode);
            }
        });
    }
};
/**
 * Global permission control */
export const filterGlobalPermission = (el, binding, vnode) => {
    let permissionList = [];
    let authList = JSON.parse(localStorage.getItem('LOGIN_USER_BUTTON_AUTH') || "[]");
    for (let auth of authList) {
        permissionList.push(auth);
    }
    if (!permissionList.length) {
        el.parentNode.removeChild(el);
        return;
    }
    let permissions = [];
    for (let item of permissionList) {
        permissions.push(item.permission);
    }
    if (!permissions.includes(binding.value)) {
        el.parentNode.removeChild(el);
    }
}
export default hasPermission;

index.js under the utils file

Other js files in the utils folder can also be exported in index.js

import hasPermission from './hasPermission'
export { hasPermission }

Introduced in main.js

import { hasPermission } from '@/utils'
Vue.use(hasPermission)

Use v-has in the component to determine whether to display the button based on the button permissions

<el-button v-has="'sys:arch:add'" type="primary" size="mini" icon="el-icon-plus" @click="add('1')">
    Add </el-button>

Summarize

This is the end of this article about Vue custom v-has directive to implement button permission judgment. For more relevant Vue custom v-has directive content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Getting Started with Vue 3.0 Custom Directives
  • Detailed explanation of Vue custom instructions and their use
  • How to build a drag and drop plugin using vue custom directives
  • Detailed explanation of custom instructions for Vue.js source code analysis
  • Vue basic instructions example graphic explanation
  • Summary of Vue 3 custom directive development
  • Vue3.0 custom instructions (drectives) knowledge summary
  • 8 very practical Vue custom instructions
  • Detailed explanation of custom instructions in Vue
  • Analysis of the implementation principle of Vue instructions

<<:  Solve the group by query problem after upgrading Mysql to 5.7

>>:  Practical method of deleting files from Linux command line

Recommend

Personalized and creative website design examples (30)

Therefore, we made a selection of 30 combinations ...

CSS to achieve chat bubble effect

1. Rendering JD Effect Simulation Effect 2. Princ...

Detailed explanation of Linux lsof command usage

lsof (list open files) is a tool to view files op...

A brief analysis of the configuration items of the Angular CLI release path

Preface Project release always requires packaging...

Use nginx + secondary domain name + https support

Step 1: Add a secondary domain name to the Alibab...

Detailed process of decompressing and installing mysql5.7.17 zip

1. Download address https://dev.mysql.com/downloa...

Ajax responseText parses json data case study

Solve the problem that the responseText returned ...

JS array deduplication details

Table of contents 1 Test Cases 2 JS array dedupli...

Linux kernel device driver kernel linked list usage notes

/******************** * Application of linked lis...