0
0
VueHow-ToBeginner · 4 min read

How to Use Binding Value in Directive in Vue

In Vue, you can access the binding value inside a custom directive using the binding.value property in the directive's hooks. This allows you to dynamically control the element's behavior based on the value passed to the directive.
📐

Syntax

A Vue custom directive receives an object with several properties in its hooks. The binding.value holds the value passed to the directive. You use it inside hooks like mounted or updated to apply logic.

  • el: The element the directive is bound to.
  • binding: An object containing the value and other info.
  • binding.value: The value passed to the directive.
javascript
app.directive('highlight', {
  mounted(el, binding) {
    el.style.backgroundColor = binding.value
  },
  updated(el, binding) {
    el.style.backgroundColor = binding.value
  }
})
💻

Example

This example shows a custom directive v-highlight that changes the background color of an element based on the binding value passed to it.

vue
<template>
  <div>
    <p v-highlight="color">This text is highlighted.</p>
    <input v-model="color" placeholder="Enter a color" />
  </div>
</template>

<script setup>
import { ref } from 'vue'

const color = ref('yellow')
</script>

<script>
export default {
  directives: {
    highlight: {
      mounted(el, binding) {
        el.style.backgroundColor = binding.value
      },
      updated(el, binding) {
        el.style.backgroundColor = binding.value
      }
    }
  }
}
</script>
Output
A paragraph with a yellow background that changes color as you type in the input box.
⚠️

Common Pitfalls

Common mistakes when using binding values in directives include:

  • Not using binding.value and trying to access the value directly.
  • Forgetting to update the element style or behavior in the updated hook, causing stale UI.
  • Passing complex objects without handling reactivity properly.
javascript
/* Wrong: ignoring binding.value */
app.directive('wrong', {
  mounted(el, binding) {
    el.style.color = binding
  }
})

/* Right: use binding.value */
app.directive('right', {
  mounted(el, binding) {
    el.style.color = binding.value
  }
})
📊

Quick Reference

  • binding.value: The main value passed to the directive.
  • binding.arg: Optional argument passed to the directive.
  • binding.modifiers: Object with modifiers used in the directive.
  • Use mounted and updated hooks to react to changes.

Key Takeaways

Use binding.value inside directive hooks to access the passed value.
Update element behavior in both mounted and updated hooks for reactivity.
Avoid accessing the binding object directly; always use binding.value for the value.
Modifiers and arguments can provide extra control but are accessed separately from binding.value.
Test directives with dynamic values to ensure UI updates correctly.