zoukankan      html  css  js  c++  java
  • <el-input>只能输入数字,保留两位小数

    实现思路

    单独做一个组件来实现额外的功能

    只能输入数字:   监听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>
  • 相关阅读:
    手工杀毒笔记
    中国黑客名单
    SQL Server 2005 数据库知识大全
    sql server和oracle行转列的一种典型方法
    <h1><span>标签在SEO中的作用及用法
    传说能加快vs编译速度(vs2008+cf3.5)
    WPF版调色器
    SQL经典案例
    Silverlight 2 相关文章汇总
    国内一些黑客高手的联系方式
  • 原文地址:https://www.cnblogs.com/scdisplay/p/13723190.html
Copyright © 2011-2022 走看看