乐闻世界logo
搜索文章和话题

How to Register Directives Locally in Vue?

2月6日 23:56

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 directives object defines a directive named my-directive.
  • The bind hook is invoked when the directive is first bound to an element, which sets the initial style.
  • The update hook is invoked when the VNode containing the directive is updated, and it determines whether to update the element's style by comparing binding.value and binding.oldValue.

Directives registered this way are limited to the component where they are declared.

标签:Vue