I am trying to build a component based on the v-text-field from vuetify and https://github.com/rafaelkendrik/imask-vuetify/blob/master/components/html/ImaskField.vue to displaying an amount in german locale.
<template>
<v-container class="pa-0" v-if="$attrs.editable">
<v-text-field
ref="field"
:model-value="masked.value"
@input="input"
@blur="(event)=> {console.log( event.target.value,'blur');this.checkNormalize();$emit('update:modelValue', Number(this.masked.unmaskedValue))}"
v-bind="$attrs"
density="compact"
variant="outlined"
@update:model-value="() =>$emit('update:modelValue', this.masked.unmaskedValue)"
></v-text-field>
</v-container>
<v-container class="pa-0" v-else>
{{
betrag === undefined ? "" : betrag.toLocaleString('de-DE', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
})
}}
</v-container>
</template>
<script lang="ts">
import Imask from 'imask'
import KreditvertragTextField from "@/components/elements/KreditvertragTextField.vue";
const INPUT_EVENT = 'input'
export default {
name: 'ImaskField',
components: {KreditvertragTextField},
model: {
prop: 'value',
event: INPUT_EVENT
},
props: {
betrag: {
type: [String, Number],
required: false,
default: 0
},
},
data: () => ({
element: {},
masked: {},
}),
watch: {
betrag : function(val) {
this.masked.unmaskedValue = '' + val;
console.log(this.masked.value, "watch")
},
masked : function(val) {
console.log(val, "watch")
}
},
methods: {
init() {
this.element = this.$refs.field.$el.querySelector('input')
this.masked = Imask(this.element, {
mask: Number,
thousandsSeparator: '.',
scale: 2,
padFractionalZeros: true, // if true, then pads zeros at end to the length of scale
normalizeZeros: true, // appends or removes zeros at ends
radix: ',',
})
this.masked.unmaskedValue=''+this.betrag;
console.log(this.masked.value, "init")
},
input(value) {
console.log(this.masked.value, "input")
this.$emit(INPUT_EVENT, value)
},
checkNormalize() {
const isNormalized = (this.element.value === this.masked.value)
if (!isNormalized) {
this.element.value = this.masked.value
this.element.dispatchEvent(new Event(INPUT_EVENT))
}
}
},
mounted() {
this.init()
}
}
</script>
if I enter a number, the code shown the correct formatted value, but if I leave the field, the previous value is rendered. anyone has an idea why