<template>
<div>
<el-input
v-model="inputValue"
:value="formattedValue"
@input="updateValue"
@blur="onBlur"
@focus="onFocus"
placeholder="请输入数字"
/>
</div>
</template>
<script setup>
import { ref, computed } from 'vue'
// 存储原始数字
const inputValue = ref(0)
// 获取格式化后的显示值(千分位)
const formattedValue = computed(() => {
// 如果是数字,格式化为千分位
return inputValue.value.toLocaleString()
})
// 更新 inputValue 的值,确保它是一个数字
const updateValue = (event) => {
const value = event.target.value.replace(/[^0-9.]/g, '')
inputValue.value = value === '' ? 0 : parseFloat(value)
}
// 当 input 失去焦点时,格式化为千分位
const onBlur = () => {
// 失去焦点时可以添加其他验证等逻辑
}
// 当 input 获取焦点时,去掉千分位,只保留数字
const onFocus = () => {
// 用户输入时,展示纯数字
inputValue.value = inputValue.value
}
</script>
<style scoped>
/* 这里可以添加样式 */
</style>