vue custom instruction usage

Posted by nicky77uk1 on Mon, 14 Feb 2022 00:46:34 +0100

preface

1, Vue's custom instructions are divided into?

In addition to the built-in instructions of core functions, vue also allows the registration of user-defined instructions. In some cases, user-defined instructions will be used for the underlying operation of ordinary DOM elements.

User defined instructions are divided into global user-defined instructions and local user-defined instructions

Global custom directive

Via Vue Directive ('the first parameter is the name of the instruction ', {the second parameter is an object with hook function})

The following is an example:

 Vue.directive('focus', {
		// el: the element bound by the instruction, which can be used to directly operate the DOM.
		//The binding property contains one of the following objects:
      inserted: function (el) { // Inserted means called when the bound element is inserted into the parent node
        el.focus();
      }
    });

Local custom instruction

Local registration is achieved by setting the directive property in the component options option
It is defined inside the component and can only be used in the current component

The following is an example:

directives: {
        // Instruction name
        dir1: {
            inserted(el) {
                // The first parameter in the instruction is the DOM of the instruction currently in use
                console.log(el);
                console.log(arguments);
                // Operate on DOM
                el.style.width = '200px';
                el.style.height = '200px';
                el.style.background = '#000';
            }
        },
        color: { // Sets the specified font color for the element
          bind(el, binding) {
            el.style.color = binding.value;
          }
        }
	}

Hook function of custom component

Custom instructions also have hook functions like components:

An instruction definition object can provide the following hook functions (all optional):

Inserted: called when the bound element is inserted into the parent node (only the parent node is guaranteed to exist, but it may not have been inserted into the document).
bind: called only once, when the instruction is bound to the element for the first time. One time initialization settings can be made here.
Update: called when the VNode of the component is updated, but it may occur before its child VNode is updated. The value of the instruction may or may not have changed. However, you can ignore unnecessary template updates by comparing the values before and after the update (see the following for detailed hook function parameters).
componentUpdated: the VNode and its sub VNode of the instruction component are updated after all updates.
unbind: called only once when the instruction is unbound from the element.
In project: drag and drop

3, Application scenarios of custom components

Using custom components can meet some of our daily scenarios. Here are some examples of custom components:

1. Anti shake

2. Image lazy loading

3. One click Copy function

2, Application scenario of vue custom instruction

Use custom instruction background
The main form of code reuse and abstraction is component.
When you need to perform low-level operations on ordinary DOM elements, custom instructions will be used at this time
However, for large DOM changes, you should still use components
Common cases

1. Input box auto focus

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

2 drop down menu
Clicking the drop-down menu itself does not hide the menu
Click the area outside the drop-down menu to hide the menu

Vue.directive('clickoutside', {
  bind(el, binding) {
    function documentHandler(e) {
      if (el.contains(e.target)) {
       return false 
      }
      
      if (binding.expression) {
        binding.value(e)
      }
    }
    
    el.__vueMenuHandler__ = documentHandler
    document.addEventListener('click', el.__vueMenuHandler__)
  },
  unbind(el) {
    document.removeEventListener('click', el.__vueMenuHandler__)
    delete el.__vueMenuHandler__
  }
})

new Vue({
  el: '#app',
  data: {
    show: false
  },
  methods: {
    handleHide() {
      this.show = false
    }
  }
})
<div class="main" v-menu="handleHide">
  <button @click="show = !show">Click to display the drop-down menu</button>
  <div class="dropdown" v-show="show">
    <div class="item"><a href="#"> option 1 < / a > < / div >
    <div class="item"><a href="#"> option 2 < / a > < / div >
    <div class="item"><a href="#"> option 3 < / a > < / div >
  </div>
</div>
  1. Relative time conversion
    Similar to the relative time after microblogging and circle of friends released the news, such as just two minutes ago, etc
<span v-relativeTime="time"></span>
new Vue({
  el: '#app',
  data: {
    time: 1565753400000
  }
})

Vue.directive('relativeTime', {
  bind(el, binding) {
    // Time.getFormatTime() method, self supplementary
    el.innerHTML = Time.getFormatTime(binding.value)
    el.__timeout__ = setInterval(() => {
      el.innerHTML = Time.getFormatTime(binding.value)
    }, 6000)
  },
  unbind(el) {
    clearInterval(el.innerHTML)
    delete el.__timeout__
  }
})

Topics: Javascript Front-end Vue.js