In Vue, you can register directives locally within components in two ways: global registration and local registration.
Local Directive Registration
To register a directive locally within a single component, use the directives property in the component's options object. Here's a basic example:
javascript<template> <div v-my-directive>I am an element with a directive</div> </template> <script> export default { directives: { 'my-directive': { bind(el, binding, vnode) { // Called when the directive is first bound to an element el.style.backgroundColor = 'yellow'; }, update(el, binding, vnode, oldVnode) { // Called when the VNode containing the directive is updated if (binding.value !== binding.oldValue) { el.style.backgroundColor = binding.value; } } } } } </script>
In the above example:
- The
directivesobject defines a directive namedmy-directive. - The
bindhook is invoked when the directive is first bound to an element, which sets the initial style. - The
updatehook is invoked when the VNode containing the directive is updated, and it determines whether to update the element's style by comparingbinding.valueandbinding.oldValue.
Directives registered this way are limited to the component where they are declared.