Simple, quick custom directive for handling currency format inside text inputs.
Compatible with Vue 2.x
npm i vue-currency-directive || yarn add vue-currency-directive
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.
<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>
import Vue from 'vue';
import vueCurrencyDirective from 'vue-currency-directive';
Vue.directive('currency', vueCurrencyDirective);
<script>
import vueCurrencyDirective from 'vue-currency-directive';
export default {
...
data(){
amount: {
value: '',
formatted: ''
},
},
directives: {
currency: vueCurrencyDirective
},
...
}
</script>
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: ٥٥٤٬٣٤٢٫٠٠ ج.م.
Author: mahmoudZakaria90
Demo: https://jsfiddle.net/Zak90/sxd9j3uL/39/
Source Code: https://github.com/mahmoudZakaria90/vue-currency-directive
#vuejs #vue #javascript