Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Before learning the Vue custom instruction of the foundation, first to lay a good foundation. And custom instructions -UI permission verification/click button elements display water ripple effect. Today to learn Vue small knowledge – common instruction (three) custom instruction binding dynamic data

Vue dynamic instruction

The parameters of an instruction can be dynamic. For example, in v-myDirective :[argument]=”value”, the argument argument can be updated based on component instance data! This allows custom instructions to be used flexibly in applications.

Here simple learning according to the dynamic data binding instructions, to control the display of the button, more functions can be added, for example: button style dynamic display, according to the background interface return

Let’s start with static styles

The simple logic of the static style is to replace the static data with the data returned by the requested back-end interface and control the display

<div class="btns">
  <! -- Control display by incoming content -->
  <button v-permission="' 1 '">Permission button -teamLeader</button>
  <button v-permission="' 2 '">Permission button -</button>
  <button v-permission="' 3 '">Permission button -test</button>
  <! --> < span style = "max-width: 100%; clear: both;
  <button v-permission="' 5 '">Permission button - Student</button>
</div>
Copy the code

Dynamic effect

Replace the data with the requested data

// src/directives/permission.js

function checkArray(key) {
  let perArray = ['1'.'2'.'3'.'4'.'default']
  let index = perArray.indexOf(key)
  if (index > -1) {
    return true // If you have this item, you have permission
  } else {
    return false // Otherwise, no permission is granted}}const permission = {
  inserted: function (el, binding) {
    let permission = binding.value // The value of the instruction permission is obtained with the binding parameter
    if (permission) {
      let hasPermission = checkArray(permission)
      if(! hasPermission) {// Delete the corresponding Dom element if you do not have permission
        console.log('el: ', el)
        console.log('el.parentNode: ', el.parentNode)

        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  },
}

export default permission
Copy the code