Translate

Wednesday 17 January 2024

What are the hook functions provided by directives in Vuejs explain with example? 064

 What are the hook functions provided by directives in Vuejs explain with example?


Directives in Vue.js offer lifecycle hooks that provide access to different stages of their interaction with the DOM, allowing you to implement custom behavior and modify elements at specific points. Here are the key hook functions:

1. bind:

  • Trigger: Called once when the directive is first bound to the element.

  • Purpose: Used for one-time setup tasks.

  • Example:


JavaScript

Vue.directive('highlight', {
  bind(el) {
    el.style.backgroundColor = 'yellow'; // Apply initial highlighting
  },
});

2. inserted:

  • Trigger: Called after the element is inserted into the DOM.

  • Purpose: Used for actions requiring the element's presence in the DOM.

  • Example:


JavaScript

Vue.directive('focus', {
  inserted(el) {
    el.focus(); // Focus the element after it's inserted
  },
});

3. update:

  • Trigger: Called whenever the bound value or data changes.

  • Purpose: Used to update the element based on the new value.

  • Example:


JavaScript

Vue.directive('resize-text', {
  update(el, binding) {
    el.style.fontSize = binding.value + 'px'; // Adjust font size based on bound value
  },
});

4. componentUpdated:

  • Trigger: Called after the component and its children have been updated.

  • Purpose: Used for actions requiring the latest state of the component.

  • Example:


JavaScript

Vue.directive('track-changes', {
  componentUpdated(el, binding) {
    console.log('Element value changed:', el.textContent);
  },
});

5. unbind:

  • Trigger: Called before the directive is unbound from the element.

  • Purpose: Used for cleanup tasks.

  • Example:


JavaScript

Vue.directive('animate', {
  unbind(el) {
    el.classList.remove('animated'); // Remove animation class
  },
});

Understanding these hooks is crucial for creating effective directives. Choose the appropriate hook for your specific needs and ensure the directive performs its intended behavior at the correct stage.


No comments:

Post a Comment

Note: only a member of this blog may post a comment.