🎉 Vue to build large single-page e-commerce applications open source! Click me to see the source 🚀🚀

Estimated reading time :3 minutes

What is an instruction?

Vue from sweet little white to leather big guy series (2) V – command

The hook function argument of the directive

What is a custom directive?

In the field of front-end development, the previous common framework was jQuery, and jQuery and the common components built on top of it form a vast production system. Angular, React, and Vue are common frameworks, and each framework needs to build a new component library based on itself. The original general components, whether pure JS or jquery-based, can be directly absorbed without transformation or reconstruction. Custom instructions can easily realize a large number of repetitive things through a short instruction.

  • Function: Perform DOM operations
  • Use scenarios: Perform low-level operations on pure DOM elements, such as text boxes to get focus
  • There are two kinds of instructions: 1 global instruction 2 local instruction

Custom global directives

  • Purpose: Defines an instruction that can be used globally
  • The key code: Vue. Directive ()
  • Suggestion: It is best to create a separate file and import it into the main.js file for separate management
// The first argument is the directive name. // The second argument is the configuration object, specifying the directive's hook function vue.directive ('directiveName'{/ /bindYou can only perform DOM operations on the element itself, not on the parent element. This is where you can perform one-time initialization Settings.bind(el, binding, vnode) {// el: the element bound by the directive can be used to manipulate the DOM directly. // Binding: an object containing the following attributes: // name: directive name, excluding the v- prefix. // value: the binding value of the directive, the value after the equals sign. // oldValue: The previous value of the directive binding, available only in update and componentUpdated hooks. Available regardless of whether the value changes. // expression: string expression after the equal sign // arg: parameter passed to the instruction, optional. For example, in v-my-directive:foo, the parameter is"foo". // modifiers: directive modifiers For example, in v-directive.foo.bar, the modifier object is {foo:true, bar: true}. // vnode: virtual node generated by Vue compilation. // oldVnode: the last virtual node, available only in update and componentUpdated hooks. Inserted (el, binding, vnode) {}, // update(el, Binding, vnode,oldVnode) {}, componentUpdated (EL, binding, vnode,oldVnode) {}, Call unbind (el) {// The element on which the instruction is located disappears from the page, triggering}}) // short if you want to use thebindTrigger the same behavior as update, regardless of the other hooks: vue.directive ('Custom directive name'.function(el, binding) {}) // example: vue.directive ('color'.function(el, binding) {el.style.color = binging. Value}"'red'"
<p v-color="'red'"></p>
Copy the code

※ The following method is recommended to organize global components

  • 1. Create one firstdirective.jsThe file then writes the global custom component. For example, I want to define a custom component that directly changes the Dom color and text size
export default (Vue) => {
    Vue.directive('dColor', {
        inserted: function(el, binding) { el.style.color = binding.value; }}); Vue.directive('dFont', {
        inserted: function (el, binding) {
            el.style.fontSize = binding.value + "px"; }}); }Copy the code
  • 2. Import it in the main.js filedirective.jsFile and call her with vue.use (directive)
import Vue from 'vue';
import App from './App.vue';
import directive from './directive';

Vue.config.productionTip = false; Vue.use(directive); New Vue({render: h => h(App),})$mount('#app')

Copy the code
  • 3. Call your component name where you want to use it, always add v- oh!
<template>
    <div class="hello">
        <p v-dColor="'red'"> I am globally defined component to modify color values </p> <p v-dFont="' 50 '"</p> </div> </template>Copy the code

Custom local directives

  • Purpose: Defines an instruction that can only be used by local components
  • Usage scenarios: Certain Dom manipulation methods that are frequently reused in components are only used in this component
  • Directives: Write a local directive that defines an INPUT automatic focus directive
<script>
export default {
    name: 'HelloWorld'// Specifies the name of the component. AutoFocus: {// The hook function is called when the bound element is inserted into the parent (the parent is called if it exists and does not need to exist in the document). inserted (el) { el.focus(); console.log('inserted'); }, // only once, when the directive is first bound to an element. Use this hook function to define an initialization action that will be performed once at binding time.bind () {
                console.log('bind'); }, // called when the component's VNode is updated, but may occur before its child's VNode is 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 updateupdata () {
                console.log('updata'); }, // called when the vNodes of the component and its children are all updated.componentUpdated () {
                console.log('componentUpdated'); }, // only called once, when the instruction is unbound from the element.unbind () {
                console.log('unbind');
            }
        }
    }
}
</script>
Copy the code

4. Call V-autofocus directly where needed

<template>
    <div class="hello">
        <p v-dColor="'red'"> I am globally defined component to modify color values </p> <p v-dFont="' 50 '"> I am globally defined components that can change size </p> <inputtype="text"
               placeholder="Please enter text"
               v-autoFocus>
    </div>
</template>
Copy the code

After reading this article, I do not know whether the warrior in front of the real learned to customize the command, their own hands to write a global command and local command, global command must be placed separately in a folder management oh 😆 refuel, front-end sweet white….

If my sharing inspires the hero in front of me, don’t hesitate to encourage me with the highest courtesy of a programmer: like ✨, comment and share.

Concern about the public number reply: learn to receive the front end of the latest and most complete learning materials, but also into the group and big guy together to learn and exchange.

Jabbed at my front-end advanced Blog