A quick custom directive for handling currency format inside text inputs

Vue-currency-directive

Simple, quick custom directive for handling currency format inside text inputs.

Installation

npm i vue-currency-directive || yarn add vue-currency-directive

Usage

  • Register in your data() a main state object e.g. amount and inside it 2 main properties value and formatted.
  • You mainly get 2 outputs: one for the unformatted/original value and the other for the formatted value.

In DOM/Single-file-component

<input v-currency:<currency?>[<locale?>]="<bindingExpression>">

For example:

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

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

      foo: {
        value: '',
        formatted: ''
      },

      bar: {
        value: '',
        formatted: ''
      }
    }
  }
}
...
<script>

Global registration

import Vue from 'vue';
import vueCurrencyDirective from 'vue-currency-directive';

Vue.directive('currency', vueCurrencyDirective);

Local registration

<script>
import vueCurrencyDirective from 'vue-currency-directive';
export default {
  ...
  data(){
    amount: {
      value: '', 
      formatted: ''
    }, 
  },
  directives: {
    currency: vueCurrencyDirective
  },
  ...
}
</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: ٥٥٤٬٣٤٢٫٠٠ ج.م.‏ 

GitHub