继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

基于 elementUI 二次封装的 Format 输入框 组件

SOHO树叶
关注TA
已关注
手记 56
粉丝 61
获赞 656

最近封装了一个可以自带format的输入框组件,效果如下:

https://img2.mukewang.com/5bd95df40001c98103640053.jpg

我所封装的组件代码如下:

<template>
  <div>
    <el-input v-model="startValue"
         @blur="startInput" 
         :maxlength="maxlength"></el-input>
    <i class="el-icon-minus padding-top-5"></i>
    <el-input v-model="endValue"
          @blur="endInput" 
          :maxlength="maxlength"></el-input>
  </div>
</template>

<script>
export default {
  name: "input-format-range",
  props:['startName','endName','maxlength'],
  data:()=>({
    startValue:'',
    endValue:''
  }),
  methods:{
    checkInput({value}){
      value=value?parseFloat(value.toString().replace(/[^0-9._-]/g, ''))||0:'';
      let formattedValue = '';
      if (value !== 0 && value !== '')
          formattedValue = Number(value)
                   .toFixed(2)
                   .replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g,'$&,');
       else
        formattedValue = value;
        
      return formattedValue;
    },
    startInput({target}){
      this.startValue = this.checkInput(target);
      this.$emit('checkInput',{startValue:this.startValue,
                               startName:this.startName,
                               endValue:this.endValue,
                               endName:this.endName});
    },
    endInput({target}){
      this.endValue = this.checkInput(target);
      this.$emit('checkInput',{startValue:this.startValue,
                               startName:this.startName,
                               endValue:this.endValue,
                               endName:this.endName});
    }
  }
}
</script>

如果传给后台要纯数字类型,你还需要去掉里面的逗号,你可以在main.js里面定义如下函数:

Vue.prototype.splitValue = function (value) {
  value = value? parseFloat(value.replace(/,/g ,'')) || 0 : '';
  return value
};

在父组件中就可以愉快的使用了~:

<template>
      <inputFormatRange @checkInput="checkPrice"
                :maxlength="9"
                :startName="'costPriceFrom'"
                :endName="'costPriceTo'"></inputFormatRange>
</template>

<script>
import inputFormatRange from '@/components/inputFormatRange.vue'
export default {
  name: "price-manage",
  components:{inputFormatRange},
  data:()=>({
    getTable:{
      costPriceFrom: '',
      costPriceTo: ''
     }
  }),
  methods:{
    checkPrice(obj){
      this.getTable[obj.startName] = this.splitValue(obj.startValue);
      this.getTable[obj.endName] = this.splitValue(obj.endValue);
    }
  }
}
</script>


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP