Detailed Explanation of Vue3 app.directive() Function


Vue3 全局 APIVue3 Global API

app.directive()is a very powerful function that allows developers to define custom global directives.

Directives are a special feature provided by Vue, used to directly manipulate DOM elements. By usingapp.directive(), you can define your own directives and use them throughout the application.


1. What is a directive?

Directives are special attributes in Vue that start withv-. Vue has some built-in commonly used directives, such asv-if、v-for、v-bindetc. These directives can help us manipulate DOM elements more conveniently.

For example,v-ifthe directive can decide whether to render an element based on the value of an expression:

Example

<div v-if="isVisible">display content</div>

WhenisVisibleistruewhendivthe element will be rendered; otherwise,divthe element will not be rendered.


2. Custom Directives

In addition to built-in directives, Vue also allows us to define our own directives. Custom directives can be used to handle specific DOM operations, such as auto-focus, scroll listening, etc.

In Vue3, we can use theapp.directive()function to register a global directive.


3. Basic Usage of app.directive()

app.directive()The function accepts two parameters:

  • Directive name:Define the name of the directive. Note that it should not include thev-prefix.
  • Directive object:An object containing directive hook functions, used to define the behavior of the directive.

3.1 Register a Simple Directive

Suppose we need to define a directive that automatically focuses on the element when it is inserted into the DOM. We can implement it like this:

Example

import { createApp } from 'vue';

const app = createApp({});

app.directive('focus', {
  mounted(el) {
    el.focus();
  }
});

app.mount('#app');

In this example, we define a directive namedfocusdirective. When the element is inserted into the DOM, themountedhook function will be called, andel.focus()will make the element automatically gain focus.

3.2 Using Custom Directives

When using a custom directive in a template, you need to add thev-prefix:

Example

<input v-focus />

When the page loads, theinputelement will automatically get focus.


4. Directive Hook Functions

Custom directives can contain multiple hook functions to perform specific operations at different lifecycle stages. Common hook functions include:

  • mounted: called when the element of the directive is inserted into the DOM.
  • updated: called when the component of the directive updates.
  • unmounted: called when the element of the directive is removed from the DOM.

4.1 Example: Listening to Scroll Events

Suppose we need to perform some operations when the user scrolls the page. We can define ascrolldirective:

Example

app.directive('scroll', {
  mounted(el, binding) {
    const handler = binding.value;
    el.addEventListener('scroll', handler);
  },
  unmounted(el, binding) {
    const handler = binding.value;
    el.removeEventListener('scroll', handler);
  }
});

In this example, themountedhook function is used to add a scroll event listener, and theunmountedhook function is used to remove the listener.

4.2 Using the Scroll Directive

Example

<div v-scroll="onScroll" style="height: 200px; overflow-y: scroll;">
<p>Scroll content...</p>
</div>

Define theonScrollmethod in the component:

Example

methods: {
  onScroll(event) {
    console.log('User is scrolling', event);
  }
}

When the user scrolls thedivelement,onScrollthe method will be called.


5. Directive Parameters and Modifiers

Custom directives can accept parameters and modifiers. Parameters are the part after the colon in the directive name, and modifiers are the part after the dot in the directive name.

5.1 Example: Using Parameters and Modifiers

Suppose we need to define acolordirective that sets the element's background color based on the parameter:

Example

app.directive('color', {
  mounted(el, binding) {
    const color = binding.arg || 'red';
    const modifiers = binding.modifiers;
    if (modifiers.bold) {
      el.style.fontWeight = 'bold';
    }
    el.style.backgroundColor = color;
  }
});

Use it in the template:

Example

<div v-color:blue.bold>Background color is blue, font is bold</div>

In this example, theblueis the parameter of the directive, andboldis the modifier.


Vue3 全局 APIVue3 Global API

Other Extensions