preface

In the front-end basic interview, Vue’s command is a frequent interview question

Interviewer asks: What instructions does Vue have?

As of Vue3.2, Vue has 16 built-in commands, including:

V-text, V-HTML, V-show, V-if, V-else, V-else -if, V-for, V-ON, V-bind, V-model, V-slot, V-pre, V-cloak, V-once, V-memo, V-is, The V-Memo is added in 3.2, and v-IS is deprecated in 3.1.0

If the interviewer further asks: How to encapsulate a custom directive?

You tell him: custom instruction should be divided into global custom instruction and local instruction; In Vue3 a global custom directive can be registered using directive() on the application instance. If local directives are required, configure the Directives option in the component to register local directives

After reading this article, you will have a comprehensive understanding of the 16 Vue directives and how to customize one

The body of the

Let’s start with a brief introduction to the instructions

1. Introduction

1.1 What is the Vue directive

In Vue, directives are simply special attributes

Vue will do something behind the scenes according to the command. And what exactly will Vue do according to the command

1.2 What are its features

An obvious feature of Vue instructions is that they all start with v-, for example, V-text

<span v-text="msg"></span>
Copy the code

2. Built-in instructions

2.1 What are the built-in instructions of Vue

Built-in instructions refer to the Vue built-in instructions, out of the box

Vue has 16 built-in commands, including:

V-text, V-HTML, V-show, V-if, V-else, V-else -if, V-for, V-ON, V-bind, V-model, V-slot, V-pre, V-cloak, V-once, V-memo, V-is, The V-Memo is added in 3.2, and v-IS is deprecated in 3.1.0

Let’s take a look at the basic uses of these built-in commands

2.2 Understand the basic use of 16 built-in instructions

2.2.1 v – text

V-text is used to update the textContent of an element, for example:

<h1 v-text="msg"></h1>
Copy the code

The content of the H1 element ultimately depends on the value of MSG

2.2.2 v – HTML

Much like V-text, except v-HTML is used to update the innerHTML of an element, for example

<div v-html="'<h1>Hello LBJ</h1>'"></div>
Copy the code

Note that the content must be inserted as normal HTML

2.2.3 v – show

V-show can switch the display value of an element based on whether the expression is true or false. It is used to control the display and hiding of elements. For example:

As you can see, this instruction triggers transition effects that show or hide when conditions change

Note that v-show does not support

2.2.4 v – the if

V-if is used to conditionally render elements based on the expression’s true or false values

In contrast to V-show, V-if destroys or rebuilds elements when switching, rather than simply showing and hiding

You can see that when the expression is false, V-if destroys the element directly, whereas V-show is visually hidden

And v-if can be

2.2.5 v – else

V-else does not need an expression to add an “else block”, equivalent to displaying v-if elements if v-if conditions are met, otherwise displaying V-else elements, for example:

Note: The v-else sibling must have either v-if or V-else -if

2.2.6 v – else – the if

Similarly, the “else if block” representing v-if, like v-else, must have v-if or V-else -if for the preceding sibling element, for example:

2.2.7 v – for

V-for an instruction for iteration that renders an element or template block multiple times based on the source data, for example:

You can also specify an alias for the array index or a key for the object

<div v-for="(item, index) in items"></div>
<div v-for="(value, key) in object"></div>
<div v-for="(value, name, index) in object"></div>
Copy the code

2.2.8 v – on

V-on is used to bind events to elements and can be abbreviated to @

The modifier

  • .stop – Call event.stopPropagation()
  • .prevent – Call event.preventdefault ()
  • .capture – Capture mode is used when adding event listeners
  • .self – The callback is triggered only if the event is triggered from the listener bound element itself
  • .{keyAlias} – The callback is triggered only if the event is triggered from a specific key
  • .once – Only one callback is triggered
  • .left – Triggered only when the left mouse button is clicked
  • .right – Triggered only when the right mouse button is clicked
  • .middle – Triggered only when the middle mouse button is clicked
  • . Passive – {passive: true} Mode Add a listener

Such as:

<! Stop bubbling -->
<button @click.stop="doThis"></button>
Copy the code

Note that when used on normal elements, you can only listen for native DOM events. When used on custom element components, it can also listen for custom events triggered by child components

2.2.9 v – bind

V-bind is used to bind data and element attributes and can be abbreviated to: or.(when using the.prop modifier), for example

<div :someProperty.prop="someObject"></div>
<! -- Equivalent to -->
<div .someProperty="someObject"></div>
Copy the code

Three modifiers for V-bind

  • .camel– Convert the kebab-case attribute name to camelCase
  • .prop– Enforces a binding to a DOM property. 3.2 +
  • .attr– Forces a binding to be a DOM attribute. 3.2 +

2.2.10 v – model

V-model is limited to: < SELECT >

The v-model has three modifiers:

  • .lazy– Lazy updates, listening for change instead of input events
  • .number– The input string is converted to a valid number
  • .trim– Enter the first and last Spaces for filtering

Two-way bindings can be created on form controls or components, for example:

2.2.11 v – slot

V-slot Is used to provide named slots or slots that need to receive prop

The optional parameter is the name of the slot. The default value is default

2.2.12 v – pre

The v-pre directive is used to skip compilation of this element and its children, for example:

You can see that the stuff inside is not compiled

2.2.13 v – cloak

The V-cloak directive is mainly used to solve the problem of interpolation flashing on the page

<div v-cloak>
  {{ message }}
</div>
Copy the code
[v-cloak] {
  display: none;
}
Copy the code

This div will only be displayed after compilation

2.2.14 v – once

The V-once directive is used to indicate that the element/component and all its children are treated as static and skipped when rendering again

2.2.15 v – 3.2 + memo

The subtree used to cache a template

The instruction takes a fixed length array of dependent values for memory comparison. If every value in the array is the same as when it was last rendered, the update of the entire subtree is skipped

<div v-memo="[valueA, valueB]"></div>
Copy the code

When rerendering, if valueA and valueB remain unchanged, updates to the

and all of its children will be skipped

2.2.16 v – is

Deprecated in 3.1.0 and replaced with :is

<component :is="currentView"></component>
Copy the code

3. Custom commands

3.1 How to customize a command

3.1.1 Global Custom Instruction

We also mentioned that in Vue3 you can register a global custom directive with directive() on an application instance. Take the example given by the authorities

const app = Vue.createApp({})
// Register a global custom directive 'V-focus'
app.directive('focus', {
  // When the bound element is mounted into the DOM...
  mounted(el) {
    // Focus elements
    el.focus()
  }
})
Copy the code

In the above code, vue.createApp ({}) is used to get the app instance. The app instance has a directive(), which creates a global custom directive

It’s very simple to use, for example

<input v-focus />
Copy the code

3.1.2 Register local directives

If you want to register local directives, configure the Caching option in the component to register local directives. Again, take v-Focus as an example:

directives: {
  focus: {
    // The definition of a directive
    mounted(el) {
      el.focus()
    }
  }
}
Copy the code

3.1.3 doubt

From the above examples we can see that both the directive custom global directive and the directives local directive are configured with a directive name such as Focus. Directives

What is Mounted in the configuration object? What is el in Mounted? What other parameters besides Mounted, what other parameters besides EL?

3.1.4 Hook Functions (7)

Mounted is a hook function that is invoked when a component is mounted. El is the element to which the directive is bound

Mounted Specifies a mounted instruction hook. Mounted specifies a mounted instruction hook

  • created: called before the attribute or event listener of the bound element is applied
  • beforeMountCalled when the directive is first bound to an element and before the parent component is mounted
  • mounted: called after the parent component of the bound element has been mounted
  • beforeUpdate: called before updating the VNode containing the component
  • updated: called after the VNode containing the component and its children are updated
  • beforeUnmount: called before uninstalling the parent component of the bound element
  • unmounted: is called only once when the directive is unbound from an element and the parent component is unmounted

3.1.5 Four arguments to the hook function

The four arguments to the hook function are optional, respectively

  • el: is used to manipulate the DOM directly, representing the element to which the directive is bound
  • bindingObject: contains the following six properties
Value: the value passed to the directive oldValue: the previous value arg: the parameters passed to the directive modifiers: dir: an object that is the configuration object passed to the directive when it is registeredCopy the code
  • vnode: virtual DOM, a blueprint of real DOM elements, corresponding to EL
  • prevNode: Indicates the previous virtual node

3.2 Manually Encapsulating custom instructions

With the basics in mind, we can manually encapsulate a custom instruction, v-PIN, to pin something to a page

3.2.1 Creating a Vue Project

First, build the Vue3 project using Vite

npm init vite@latest
Copy the code

Finally, use NPM run dev to start the project as prompted

Of course you can do it the other way

We know that Vue custom instructions have two ways of global registration and local registration. For convenience, I will register the V-PIN globally

3.2.2 Implementation effect

I want to talk about arbitrary location, such as the logo in the upper right corner, the code is as follows:

//main.js
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)

app.directive('pin', {
    mounted(el, binding) {
        // Do you want to freeze
        var pinned = binding.value;
        // Where is the modifier passed in
        var position = binding.modifiers;
        // The argument passed to the instruction can indicate the importance of the fixed
        var args = binding.arg;
        if (pinned) {
            el.style.position = 'fixed';
            if (args == "warning") {
                // Simply set the styles to distinguish between them
                el.style.backgroundColor = "pink";
            }
            for (var val in position) {
                if (position[val]) {
                    el.style[val] = '10px'; }}}else {
            el.style.position = 'static';
            el.style.backgroundColor = "";
        }
    }
})

app.mount('#app')
Copy the code

It is also very simple to use, as follows

The result is shown below:

3.2.3 Improve the structure

In order to register more custom instructions in the future, we modify the code structure

First, create a new folder directives specifically for holding instructions. Caching

Then write each custom directive as an object and export it as follows directives\pin.js

const pin = {
  mounted(el, binding) {
    // Do you want to freeze
    var pinned = binding.value;
    // Where is the modifier passed in
    var position = binding.modifiers;
    // The argument passed to the instruction can indicate the importance of the fixed
    var args = binding.arg;
    if (pinned) {
      el.style.position = 'fixed';
      if (args == "warning") {
        el.style.backgroundColor = "pink";
      }
      for (var val in position) {
        if (position[val]) {
          el.style[val] = '10px'; }}}else {
      el.style.position = 'static';
      el.style.backgroundColor = ""; }}}export default pin
Copy the code

Then, create index.js under the Directives folder, import all the directives there, put them in the directives, and export an install method. Directives

import pin from './pin'
const directives = {
    pin
}
export default {
    install(app) {
        Object.keys(directives).forEach((key) = > {
            app.directive(key, directives[key])
        })
    },
}
Copy the code

Finally, in main.js, the install method is called with use(), and all directives are registered in bulk

import { createApp } from 'vue'
import App from './App.vue'
import Directives from './directives'


const app = createApp(App)

app.use(Directives)

app.mount('#app')
Copy the code

After refreshing, the result is the same

The advantage is that it is much easier to write custom instructions later

conclusion

In this article, we learned about 16 Vue directives and how to manually encapsulate a custom directive

That’s all for this article. If you have any questions, please leave a comment at 🌹