demand

You can see that the input box above is not autofocus when refreshing the page, so you can use a custom focus() method to handle this. And can I set the value in the text box and the color of the font when I refresh the page? Is it possible to set the font color by passing an argument?

These can be implemented based on Vue’s custom instructions.

Introduction to the

In addition to the core functionality’s default built-in directives (V-model and V-show), Vue also allows the registration of custom directives. Note that in VU 2.0, the main form of code reuse and abstraction is components. However, there are cases where you still need to perform low-level operations on normal DOM elements, and custom directives are used.

For the above requirements, you need to customize a focust method of focus.

This element gets focus when the page loads (note: Autofocus doesn’t work on mobile Safari). In fact, as long as you haven’t clicked on anything since opening the page, the input box should remain in focus. Now let’s implement this function with a directive:

// 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()}})Copy the code

If you want to register local directives, the component also accepts a caching option:

Reported: {focus: {// Definition of the directivefunction (el) {
      el.focus()
    }
  }
}
Copy the code

You can then use the new V-focus attribute on any element in the template, as follows:

<input v-focus>
Copy the code

The inserted hook function was used in the above custom directive, and there are more hook functions.

Hook function

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

  • Bind: Called only once, the first time a directive is bound to an element. This is where you can perform one-time initialization Settings.

  • Inserted: Called when the bound element is inserted into a parent (the parent is guaranteed to exist, but not necessarily inserted into the document).

  • Update: called when the component’s VNode is updated, but may occur 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: Invoked when the VNode of the component where the directive resides and its child VNodes are all updated.

  • Unbind: Called only once, when an instruction is unbound from an element.

Bind: Initializes the input box values and font styles in the list

Bind: Called only once, the first time a directive is bound to an element. This is where you can perform one-time initialization Settings. Bind only handles element styles, values, and other attributes. It does not handle JS functions because many js functions need to be inserted into dom memory. Consider that bind performs the behavior before window.onload.

        directives: {
            focus: {
                bind: function(el) {// This is executed immediately whenever an instruction is bound to an elementbindFunction, which is executed only once In each function, the first argument, always el, represents the element to which the instruction is bound. The el argument is a native JS object that has not yet been inserted into the DOM at the time the instruction is bound. // El.focus () // When binding elements, you can set the initial value el.value ='bind func';
                    el.style.color = 'blue';
                    el.style.fontWeight = '700';
                },
Copy the code

In this case, the focus() method is a JS action that requires the element to be inserted into DOM memory to be valid, so I only set the element’s content and style.

Inserted: Implements the focus requirement in the list

[insert] [insert] [insert] [insert] [insert] [insert] [insert] So the js methods that execute relative are put into the INSERTED to be processed.

First register a local directive in the VM as follows:

On the input box, set the custom V-focus command as follows:

Refresh the page and the following information is displayed:

As you can see from the page, the input box executes both the bind and the INSERTED methods.

Bind: bind: bind: bind: bind: bind: bind: bind: bind: bind: bind: bind

Let’s look at the parameters of the hook function (that is, EL, Binding, vNode, and oldVnode).

Hook function arguments

The instruction hook function is passed the following arguments:

  • el: the element bound by the directive that can be used to manipulate the DOM directly.
  • binding: an object containing the following properties:
    • name: Indicates the command namev-Prefix.
    • value: The binding value of the directive, for example:v-my-directive="1 + 1", the binding value is2.
    • oldValue: The value preceding the instruction binding, only inupdate 和 componentUpdatedHooks are available. Available regardless of whether the value changes.
    • expression: Command expression in the form of a string. For example,v-my-directive="1 + 1"Where, the expression is"1 + 1".
    • arg: Optional parameter passed to the instruction. For example,v-my-directive:fooWhere, the parameter is"foo".
    • modifiers: an object that contains modifiers. Such as:v-my-directive.foo.bar, the modifier object is{ foo: true, bar: true }.
  • vnode: virtual node generated by Vue compilation. movingVNode APITo learn more.
  • oldVnode: Indicates the last virtual nodeupdate 和 componentUpdatedHooks are available.

All parameters except el should be read-only and should not be modified. If you need to share data between hooks, it is recommended to do so through the element’s dataset.

I’m a little confused by the hook parameters, but that’s okay. So let’s write an example and print out the information to get a sense of what’s going on.

Prints the parameter information of the hook function

This print information, I mainly print these several commonly used parameters, used to set the above input box font color.

  • binding: an object containing the following properties:
    • name: Indicates the command namev-Prefix.
    • value: The binding value of the directive, for example:v-my-directive="1 + 1", the binding value is2.
    • expression: Command expression in the form of a string. For example,v-my-directive="1 + 1"Where, the expression is"1 + 1".

First, I set a binding value for the custom command as follows:

<input v-focus="'green'"
Copy the code

Note: I set it to be a string ‘green’ because I’m going to use it for styling later.

Let’s first print out what these three parameters show.

The following information is displayed:

Now you can set the font color of the style based on the provided binding value, as follows:

Refresh the browser as follows:

Function shorthand

In many cases, you might want to trigger the same behavior with bind and UPDATE and not care about the other hooks. For example:

Vue.directive('color-swatch'.function (el, binding) {
  el.style.backgroundColor = binding.value
})
Copy the code

This is the way to write the global custom instruction, and this is the way to write the local custom instruction, as follows:

First bind a custom directive v-fontSize to the element.

Then define the shorthand custom directive as follows:

        directives: {
            'fontsize': function(el, binding) {// Note thisfunctionIt's the same as writing the codebindUpdate el.style.fontSize = parseInt(binding.value) +'px'
            },
            'focus': {
                bind: function(el,binding) {// This is executed immediately whenever the directive is bound to an elementbindFunction, which is executed only once In each function, the first argument, always el, represents the element to which the instruction is bound. The el argument is a native JS object that has not yet been inserted into the DOM at the time the instruction is bound. // el.focus()...Copy the code

The browser displays the following information: