Vue.js货币输入掩码问题:禁用小数点仅允许逗号作为分隔符
解决方案
修改后可直接运行的完整代码如下:
Vue.component('my-currency-input', { template: ` <div> <input type="text" v-model="formattedCurrencyValue" @keydown="handleKeydown" @blur="focusOut"/> </div>`, data: function() { return { currencyValue: 0, formattedCurrencyValue: "0,00" } }, methods: { handleKeydown(e) { // 禁止小数点输入 if (e.key === '.') { e.preventDefault() } }, focusOut: function() { // 把输入的逗号替换为小数点后再做数值解析 const inputVal = this.formattedCurrencyValue.replace(',', '.').replace(/[^\d\.]/g, "") this.currencyValue = parseFloat(inputVal) if (isNaN(this.currencyValue)) { this.currencyValue = 0 } // 拆分整数和小数部分分别格式化 const [intPart, decimalPart] = this.currencyValue.toFixed(2).split('.') // 整数部分添加点作为千分位分隔符 const formattedInt = intPart.replace(/(\d)(?=(\d{3})+$)/g, "$1.") // 用逗号拼接整数和小数部分,输出目标格式 this.formattedCurrencyValue = `${formattedInt},${decimalPart}` }, } }); new Vue({ el: '#app' });
- 新增
handleKeydown方法绑定输入框keydown事件,检测到用户按下小数点时直接拦截,实现禁用小数点输入的需求 - 初始展示值调整为
0,00,符合要求的默认格式 - 优化数值解析逻辑:将用户输入的逗号(小数分隔符)先替换为小数点再做浮点转换,避免解析错误
- 重写格式化规则:拆分整数、小数部分分别处理,整数部分用点做千分位分隔符,最后用逗号拼接两部分,最终输出
0,00、1.000,00格式的内容
内容的提问来源于stack exchange,提问作者Liza
相关产品推荐
相关产品推荐

