vue使用自定义事件的表单输入组件(日期组件与货币组件)

自定义事件可以用来创建自定义的表单输入组件,使用 v-model 来进行数据双向绑定。
v-model的实现原理 :
<input v-model="something">
这不过是以下示例的语法糖:
<input
v-bind:value="something"
v-on:input="something = $event.target.value">

在开发项目中,当遇到日期数据时,往往后台的日期数据都为long型,而前台显示成日期型,在使用v-model时,需要转换一下,为了简化转换过程,对此实现自定义日期输入组件,该组件接收long型日期数据,显示为date型,通过v-model实现双向绑定

自定义日期输入组件实现代码:

dates.vue组件

<template>
      <input ref='dateinput' type="date" class="form-control" v-bind:value="svalue(value)" v-on:input="uvalue($event.target.value)" />
</template>
<script type="text/javascript">

    export default{
        props:['value'],
        methods:{
            svalue(value){
                if(value) {
                    return $api.dateFormat(value);
                }else{
                    return '';
                }
            },
            uvalue(value){
                var _val = value.split('-');
                //大于1970时才触发事件,以防止用户手动输入年份时计算不正确
                if(value && _val[0]>=1970){
                    this.$emit('input',$api.getLong(value));
                }
            }
        }
    }
    //dateFormat函数 long转date型
    var dateFormat=function(longTypeDate){ 
        var dateType = "";  
        if(longTypeDate){
            longTypeDate = parseInt(longTypeDate);
            var date = new Date(longTypeDate); 
            dateType += date.getFullYear();   //年  
            dateType += "-" + getMonth(date); //月   
            dateType += "-" + getDay(date);   //日  
        }else{
            dateType =  (new Date()).format("yyyy-MM-dd") ;
        }
        return dateType;
    } 
    //返回 01-12 的月份值   
    var getMonth=function (date){  
        var month = "";  
        month = date.getMonth() + 1; //getMonth()得到的月份是0-11  
        if(month<10){  
            month = "0" + month;  
        }  
        return month;  
    }  
    //返回01-30的日期  
    var getDay=function (date){  
        var day = "";  
        day = date.getDate();  
        if(day<10){  
            day = "0" + day;  
        }  
        return day;  
    }
    //getLong函数 date转long型
    var getLong = function(date){
        date=Date.parse(date.replace(new RegExp("-","gm"),"/"));
        return date;
    }

</script>

使用方法

<template>
    <div>
        <dates name="guaranteeBeginDay" v-model="guaranteeBeginDay" />
    </div>
</template>
<script>
    import dates from '../dates/dates.vue'
    export default{
        data(){
            return {
                guaranteeBeginDay:1509697628823 //long型数据
            }
        }
    }
</script>

项目需求,在表单中货币组件,用户输入数字,为其自动添加逗号分隔符,且只能输入数字,限制小数点后最多两位,实现了自定义货币组件

自定义货币组件实现代码:

currency.vue组件

<template>
    <input refs="currencyinput" class="form-control" type="text" v-bind:value="showValue(value)" v-on:input="updateValue($event)" />
</template>

<script type="text/javascript">

    export default{
        props:['value'],
        methods:{
            showValue(value){
                if(!!!value){
                  return '0';
                }
                return (value+'').replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
            },
            updateValue(el){
                var value = el.target.value ;
                value = value.replace(/[^\d.]/g,"")
                         .replace(/\.{2,}/g,".")
                         .replace(".","$#$").replace(/\./g,"").replace("$#$",".")
                         .replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数 
                if(value.indexOf(".") < 0 && value !=""){//以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额  
                    if(value.substr(0,1) == '0' && value.length == 2){  
                        value = value.substr(1,value.length);      
                    }  
                }
                el.target.value = value.replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');

                this.$emit('input', value);
            }
        }
    }

</script>

使用方法

<template>
    <div>
        <currency name="money" v-model="money" />
    </div>
</template>
<script>
    import dates from '../currency/currency.vue'
    export default{
        data(){
            return {
                money:12934350.34 
            }
        }
    }
</script>

实例图片
这里写图片描述

一开始不明白
自定义组件中绑定的input事件中
this.$emit('input',$api.getLong(value)); || this.$emit('input', value); 的含义
为什么input事件中还要触发input事件,这样不就造成循环调用了吗,后来深入研究,
才明白,$emit是用于子组件触发父组件的事件函数,所以此处的input事件为调用该组件的父组件的input事件
<dates name="guaranteeBeginDay" v-model="guaranteeBeginDay" /> || <currency name="money" v-model="money" />
而父组件的input事件则是v-model的实现原理
<input
v-bind:value="something"
v-on:input="something = $event.target.value">

所以子组件的input事件会触发父组件的input事件,进而改变vue data数据,data数据变化触发v-bind:value来更新页面数据显示。

猜你喜欢

转载自blog.csdn.net/hanxue_tyc/article/details/78437235