Skip to content

Commit cfbab1e

Browse files
committed
refactor: component VueNumberFormat
1 parent b1099a8 commit cfbab1e

File tree

2 files changed

+46
-67
lines changed

2 files changed

+46
-67
lines changed

src/components/VueNumberFormat.vue

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<template>
2+
<input
3+
:value="formattedValue"
4+
inputmode="numeric"
5+
@input="onInput($event)"
6+
@focus="onFocus($event)"
7+
>
8+
</template>
9+
10+
<script setup lang="ts">
11+
import { inject, computed } from 'vue';
12+
import { type VueNumberFormatOptions } from '../types/FormatOptions'
13+
import { format, setCursor, setCursorPosition, unformat } from "../utils"
14+
15+
interface Props {
16+
// TODO: validate all type of input
17+
value: string | number | null,
18+
options?: Partial<VueNumberFormatOptions>
19+
}
20+
21+
const props = defineProps<Props>();
22+
23+
// TODO: add backward compatible for v2
24+
const emit = defineEmits(['update:value'])
25+
26+
const globalOptions = inject('VueNumberFormatOptions') as VueNumberFormatOptions;
27+
28+
const mergedOptions = computed<VueNumberFormatOptions>(() => Object.assign(globalOptions, props.options))
29+
const formattedValue = computed(() => format(props.value, mergedOptions.value))
30+
31+
function onFocus($event: Event) {
32+
const target = $event.target as HTMLInputElement;
33+
setCursor(target, (target.value.length - mergedOptions.value.suffix.length))
34+
}
35+
36+
function onInput($event: Event) {
37+
const target = $event.target as HTMLInputElement;
38+
setCursorPosition(target, mergedOptions.value)
39+
const value = unformat(target.value, mergedOptions.value)
40+
updateValue(value)
41+
}
42+
43+
function updateValue(value: any) {
44+
emit('update:value', value)
45+
}
46+
</script>

src/vue-number-format.vue

Lines changed: 0 additions & 67 deletions
This file was deleted.

0 commit comments

Comments
 (0)