RegisterAddressInput.vue
2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<script lang="ts" setup>
import { InputGroup, InputNumber, Select, Input } from 'ant-design-vue';
import { watch } from 'vue';
import { unref } from 'vue';
import { computed } from 'vue';
import { ref } from 'vue';
enum AddressTypeEnum {
DEC = 'DEC',
HEX = 'HEX',
}
const emit = defineEmits(['update:value']);
const DEC_MAX_VALUE = parseInt('0xffff', 16);
const props = withDefaults(
defineProps<{
value?: string;
inputProps?: Recordable;
}>(),
{
value: '0',
inputProps: () => ({}),
}
);
const addressTypeOptions = [
{ label: AddressTypeEnum.DEC, value: AddressTypeEnum.DEC },
{ label: AddressTypeEnum.HEX, value: AddressTypeEnum.HEX },
];
const type = ref(AddressTypeEnum.DEC);
const inputValue = ref<number | string>(0);
const getHexValue = computed(() => {
return parseInt(unref(inputValue) || 0, 16);
});
const getDecValue = computed(() => {
let formatValue = Number(unref(inputValue) || 0).toString(16);
formatValue = `0x${formatValue.padStart(4, '0')}`;
return (inputValue.value as number) > DEC_MAX_VALUE ? '0x0000' : formatValue;
});
const handleEmit = () => {
const syncValue = unref(type) === AddressTypeEnum.DEC ? unref(getDecValue) : unref(getHexValue);
emit('update:value', syncValue);
};
const handleChange = (value: AddressTypeEnum) => {
const syncValue = value === AddressTypeEnum.DEC ? unref(getHexValue) : unref(getDecValue);
inputValue.value = syncValue;
emit('update:value', syncValue);
};
watch(
() => props.value,
(targetValue) => {
inputValue.value = targetValue || 0;
}
);
</script>
<template>
<InputGroup compact class="!flex">
<Select
v-model:value="type"
:options="addressTypeOptions"
@change="handleChange"
class="bg-gray-200 max-w-20"
/>
<InputNumber
v-if="type === AddressTypeEnum.DEC"
v-model:value="inputValue"
:step="1"
class="flex-1"
@change="handleEmit"
v-bind="inputProps"
/>
<Input v-if="type === AddressTypeEnum.HEX" v-model:value="inputValue" />
<div class="text-center h-8 leading-8 px-2 bg-gray-200 cursor-pointer rounded-1 w-20">
<div v-if="type === AddressTypeEnum.DEC">{{ getDecValue }}</div>
<div v-if="type === AddressTypeEnum.HEX">{{ getHexValue }}</div>
</div>
</InputGroup>
</template>