뚠뚠멍의 생각들

Creating Custom Directives in Nuxt.js

Created: 2024-09-28

Created: 2024-09-28 19:07

It's convenient to create commonly applied DOM functions across multiple pages or components


as custom directives.


I want to create a scroll directive sample.

- Useful for data loading on scroll, displaying toasts on scroll, etc., on the main screen or detail pages.


1. First, create a file and register it in the nuxt plugin.

Nuxt config plugins execute the defined files when the Nuxt application initializes, activating specific actions. = Specific functions can be used globally.


2. Implement the scroll directive.

It is implemented so that the callback function can be passed from the component.


3. Now use v-scroll on the page.



Others

There are several hooks that can be used when creating custom directives.

1. bind(el, binding, vnode)
Description: Called only once when the directive is first bound to the element.

Initial settings can be made here for the bound element.


Arguments

el: The DOM element to which the directive is bound
binding: Object containing the directive's value, expression, arguments, etc.
vnode: Virtual node created by the Vue compiler


2. inserted(el, binding, vnode)

Description: Called when the bound element is inserted into the DOM. In other words, it is used when the directive is actually added to the DOM.

* In the scroll event binding code, DOM-related operations are performed at the inserted hook point.


3. update(el, binding, vnode, oldVnode)

Description: Called whenever the attributes or values of the bound element change.

However, this is before the child components are updated.

Used when DOM execution is needed when the binding value changes.

Arguments

oldVnode: Previously rendered virtual node


4. componentUpdated(el, binding, vnode, oldVnode)

Description: Called after the attributes or values of the bound element are updated and all child components are updated.

In other words, it is executed in the final DOM state. It waits for the child component values to change before execution.


5. unbind(el, binding, vnode)

Description: Called when the directive is no longer applied to the element and the element is destroyed.

At this point, event listeners are removed, or cleanup tasks are performed.

* In the scroll custom sample, the event listener is also cleaned up at the unbind point.




Comments0