I have created a Vue component called "formatted-number" which takes in an integer value (e.g. 1234) and currently displays it as a string (e.g. "12.34") to represent a price in a textfield, with the appropriate "," or "." based on the country.
However, I want to maintain the value as an integer while displaying it as a price, allowing users to edit the "string-price" while also updating the integer value in the background.
Does anyone have any suggestions on how I can achieve this?
Below is the current code snippet:
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)
));
}
}
});