I have a vue component called "formatted-number", it receives an int value (1234) and changes it currently to a string ("12.34"), so that it is showed as an price (with "," or "." depending on the country) in a textfield.
I would like to keep the value as an int and just show it as a price, so that our users can edit the "string-price" but it also updates the int value in the background.
Do someone have a clue how I can manage this?
Here is the current code:
Vue.component('formattedNumber', {
props: ['value', 'abs'],
template: '<input type="text" :value="value" autocomplete="off" @blur="updateNumber($event.target.value)" ref="input">',
mounted: function () {
this.updateNumber(this.value / 100);
},
methods: {
separators: function () {
var comparer = new Intl.NumberFormat(navigator.language).format(10000 / 3);
return {
thousandSeparator: comparer[1],
decimalSeparator: comparer[5]
};
},
unformat: function (number) {
var separators = this.separators();
var result = number
.toLocaleString(navigator.language)
.replace(separators.thousandSeparator, '')
.replace(/[^\d.,-]/g, '')
.replace(separators.decimalSeparator, '.');
return this.abs ? Math.abs(Number(result)) : this.Number(result);
},
updateNumber: function (value) {
this.$emit('input', new Intl.NumberFormat(
navigator.language,
{minimumFractionDigits: 2, maximumFractionDigits: 2}).format(this.unformat(value)
));
}
}
});
Create a filter: docs.
Filters only change html output and leave the value intact.