vue element el-input輸入限制數字

Bivesou發表於2020-12-22

網上有很多答案都說用
οnkeyup=“value=value.replace(/[^\d]/g,’’)”
可是會導致輸入文字後v-mode無法繫結
下面這種方法親測可用

<el-input :disabled='cooperationSettingType==1' @input="handleStockRadio('thirdSalesTask')" v-model="ruleForm.thirdSalesTask" placeholder=""></el-input>

input方法繫結handleStockRadio方法

handleStockRadio(field) {
          this.ruleForm[field]= this.ruleForm[field].replace(/[^\d.]/g,''); // 清除"數字"和"."以外的字元
          this.ruleForm[field] = this.ruleForm[field].replace(/^\./g,''); // 驗證第一個字元是數字
          this.ruleForm[field] = this.ruleForm[field].replace(/\.{2,}/g,'.'); // 只保留第一個, 清除多餘的
          this.ruleForm[field] = this.ruleForm[field].replace('.','$#$').replace(/\./g,'').replace('$#$','.');
          // eslint-disable-next-line no-useless-escape
          this.ruleForm[field] = this.ruleForm[field].replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3'); // 只能輸入兩個小數
          if(field!='totalSalesTask'&&field!='firstSalesTask'&&field!='secondSalesTask'&&field!='thirdSalesTask'){
            if (this.ruleForm[field] > 100) {
                this.ruleForm[field] = 100;
            }
            }
            
          if (this.ruleForm[field] < 0) {
            this.ruleForm[field] = 0;
          }
    },

大家可用試試看

相關文章