Vue custom v-has instruction, steps for button permission judgment

Vue custom v-has instruction, steps for 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 that explains it very clearly.

//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>

The above is the detailed content of the steps of Vue custom v-has instruction and button permission judgment. For more information about Vue custom v-has instruction, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of Vue custom instructions and their use
  • Vue custom v-has instruction to implement button permission judgment
  • 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
  • Steps and complete code of vue custom directive to limit input box input value
  • Vue custom instructions and dynamic routing to achieve permission control
  • Solve the memory leak problem caused by Vue custom instructions
  • Solve the conflict between onmouseup and click events when VUE customizes drag instructions
  • Detailed explanation of custom instructions for v-bind:style effects in Vue
  • Getting Started with Vue 3.0 Custom Directives

<<:  MySQL 5.7.20 compressed version download and installation simple tutorial

>>:  Common Linux English Error Chinese Translation (Newbies Must Know)

Recommend

4 functions implemented by the transform attribute in CSS3

In CSS3, the transform function can be used to im...

MySQL 5.7.24 installation and configuration graphic tutorial

This article shares the installation and configur...

MySQL dual-master (master-master) architecture configuration solution

In enterprises, database high availability has al...

Detailed explanation of MySQL 5.7.9 shutdown syntax example

mysql-5.7.9 finally provides shutdown syntax: Pre...

Vue Element-ui table realizes tree structure table

This article shares the specific code of Element-...

MySQL 8.0 Window Function Introduction and Summary

Preface Before MySQL 8.0, it was quite painful to...

Detailed tutorial on installing nacos in docker and configuring the database

Environment Preparation Docker environment MySQL ...

js precise calculation

var numA = 0.1; var numB = 0.2; alert( numA + num...

Detailed explanation of Vue life cycle

Table of contents Why understand the life cycle W...

19 MySQL optimization methods in database management

After MySQL database optimization, not only can t...

How to modify the root user password in mysql 8.0.16 winx64 and Linux

Please handle basic operations such as connecting...