Vue输入框千分位格式化且保留数组数值类型实现问询
实现输入框千分位格式化显示同时保留数组数值类型
核心思路
不能直接用v-model绑定原数组——因为输入框需要显示带千分位的字符串,而原数组要存储数值类型。我们可以拆分v-model为:value(绑定格式化后的显示值)和@input(处理输入内容并更新原数组),同时保证输入过程中实时格式化显示,且滑块组件的数值更新能同步到输入框。
具体实现代码
Template 部分
替换原v-model为格式化后的绑定值与输入事件监听:
<template> <input type="text" class="text-center" :value="formatNumber(rangePrice[0])" @input="handleInput(0, $event)" /> <input type="text" class="text-center" :value="formatNumber(rangePrice[1])" @input="handleInput(1, $event)" /> <Slider class="slider" v-model="rangePrice" :lazy="false" :min="0" :max="100000000" :tooltips="false" /> </template>
Script 部分
实现格式化与输入处理逻辑,确保数组始终存储数值类型:
<script setup> import { ref } from 'vue' const rangePrice = ref([0, 100000000]) // 将数值格式化为带千分位的字符串 const formatNumber = (num) => { return num.toString().replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",") } // 处理输入框输入事件 const handleInput = (index, event) => { // 过滤输入中的非数字字符 const inputValue = event.target.value.replace(/\D/g, "") // 转为数值类型,空输入则设为0 const numericValue = inputValue ? Number(inputValue) : 0 // 更新原数组的数值 rangePrice.value[index] = numericValue // 实时更新输入框显示为格式化内容 event.target.value = formatNumber(numericValue) } </script>
关键细节说明
formatNumber函数:先过滤数值中的非数字字符,再通过正则添加千分位逗号,返回格式化后的字符串用于输入框显示。handleInput函数:- 过滤用户输入的非数字内容,避免无效值进入数组;
- 将处理后的内容转为数值,保证
rangePrice数组始终存储数值类型; - 手动设置输入框的显示值,实现输入过程中实时展示千分位格式。
- Slider组件:直接绑定
rangePrice数值数组,拖动滑块时会自动更新数组,输入框的:value基于数组值计算,因此会同步显示格式化后的内容,无需额外处理。
内容的提问来源于stack exchange,提问作者Jose
相关产品推荐
相关产品推荐

