DEV Community

Cover image for The power of using Vue custom directives, vue-currency-directive
Mahmoud Zakaria
Mahmoud Zakaria

Posted on

The power of using Vue custom directives, vue-currency-directive

I just want to test and see instead of creating a whole component for just handling a one specific behavior like currency format I could just use one line of a directive.

Say Hi to vue-currency-directive.
This time comes with dynamic arguments

Here is a playground:
https://jsfiddle.net/Zak90/sxd9j3uL/46/

Here is its npm:
https://www.npmjs.com/package/vue-currency-directive

Basic usage

<input v-currency="amount.value" />

Within Components/controlled inputs

You can pass directive arguments for currency and locale.
<Transaction v-currency:EUR[fr-FR]="transaction.value" />

Data()

How data is structured.

data(){
  return {
    amount: {
      value: '',
      formatted: ''
    },
    transaction: {
      value: '',
      formatted: ''
    }
  }
}

Dynamic arguments

In case you want to handle arguments in more dynamic way based on data changes and not sticking with a specific currency and locale, just add 2 more state inputs currency and locale inside the parent object e.g. amount in our case and remove any directive args e.g.:EUR[de-DE] from the component and vice-versa:

<template>
  <input v-currency="amount.value" />

  //Currency selector
  <select v-model="amount.currency">
    <option value="USD">USD</option>
    <option value="EUR">EUR</option>
    <option value="GBP">GBP</option>
  </select>

  //Locale selector
  <select v-model="amount.locale">
    <option value="en-US">US</option>
    <option value="de-DE">DE</option>
    <option value="en-GB">GB</option>
  </select>

</template>

<script>
...
export default {
  data(){
    return {
      amount: { // naming is not strict 'amount, foo, bar, ...etc'
        value: '', 
        currency: '',
        locale: '',
        formatted: '' // Better to be empty
      }
    }
  }
}
...
</script>

Examples

Passing no arguments will reflect to "USD" currency by default and for locale it will use the configured browser language.

<input v-currency="amount.value"> // amount.value = 3244
//Output: $3,244.00

Passing currency argument only without locale.

<input v-currency:EUR="amount.value"> // amount.value = 100234
//Output: €100,234.00

Passing with locale argument and different currency.

<input v-currency:EGP[ar-EG]="amount.value"> // amount.value = 554342
//Output: ٥٥٤٬٣٤٢٫٠٠ ج.م.‏ 

Top comments (0)