實現思路
單獨做一個組件來實現額外的功能
只能輸入數字: 監聽input事件,在監聽函數中通過正則處理掉非字符
保留兩位小數: 監聽blur事件,在失去焦點時格式化為2位小數,對於從prop中進來的value屬性每次都進行格式化
完整代碼
<template> <el-input v-model="inputValue" @blur="onBlur" @input="onInput"/> </template> <script> const debounce=(func,awit,immediately)=>{//防抖函數 var timer; return function(){ var self=this; if(immediately && !timer){ func.call(self) } if(timer) clearTimeout(timer); timer=setTimeout(function(){ func.call(self) },awit) } } const toDecimal2=(x)=>{//格式化函數 if(x.split('.').length>2){ x=x.split('.').slice(0,2).join('.'); } var f = parseFloat(x); if (isNaN(f)) { return '0.00'; } f = Math.round(x*100)/100; var s = f.toString(); var rs = s.indexOf('.'); if (rs < 0) { rs = s.length; s += '.'; } while (s.length <= rs + 2) { s += '0'; } return s; } export default { props:{ value:{ } }, data(){ return { inputValue:this.value, emitEvent:debounce(()=>{ this.$emit('input',this.inputValue) },1000) } }, watch:{ value(){ this.inputValue=toDecimal2(this.value) } }, methods:{ onBlur(){ this.inputValue=toDecimal2(this.inputValue); }, onInput(value){ this.inputValue = value.replace(/[^\d.]/g,''); this.emitEvent() } } } </script>