Show Content
When `isVisible` is `true`, the `div` element will be rendered; otherwise, the `div` 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 some specific DOM operations, such as auto-focus, scroll listening, etc.
In Vue3, we can register a global directive through the `app.directive()` function.
* * *
## 3. Basic Usage of app.directive()
The `app.directive()` function accepts two parameters:
* **Directive Name**: The name of the directive. Note that it should not include the `v-` prefix.
* **Directive Object**: An object containing directive hook functions, used to define the behavior of the directive.
### 3.1 Registering a Simple Directive
Suppose we need to define a directive that automatically focuses on an 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 defined a directive named `focus`. When an element is inserted into the DOM, the `mounted` hook function will be called, and `el.focus()` will automatically focus on that element.
### 3.2 Using Custom Directives
When using custom directives in templates, you need to add the `v-` prefix:
## Example
When the page loads, the `input` element will automatically get focus.
* * *
## 4. Directive Hook Functions
Custom directives can contain multiple hook functions, used to execute specific operations at different lifecycle stages. Common hook functions include:
* **mounted**: Called when the element with the directive is inserted into the DOM.
* **updated**: Called when the component with the directive is updated.
* **unmounted**: Called when the element with 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 a `scroll` directive:
## 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, the `mounted` hook function is used to add a scroll event listener, and the `unmounted` hook function is used to remove the listener.
### 4.2 Using the Scroll Directive
## Example
Scroll Content...
Background color is blue, font is bold
In this example, `blue` is the argument of the directive, and `bold` is the modifier.
* * Vue3 Global API](#)
YouTip