app-format-data.vue 2.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
<template>
  <span class="app-format-data">
    {{getcurValue()}}
  </span>
</template>
<script lang = 'ts'>
import { Component, Vue, Prop } from 'vue-property-decorator';
import moment from "moment"; 
@Component({})
export default class AppFormatData extends Vue {

  /**
   * 格式化正则
   *
   * @type {string}
   * @memberof AppFormatData
   */
  @Prop({default:'YYYY-MM-DD HH:mm:ss'}) public format?:string;

  /**
   * 类型格式
   *
   * @type {string}
   * @memberof AppFormatData
   */
  @Prop() public dataType?:string;

  /**
   * 精度
   *
   * @type {string}
   * @memberof AppFormatData
   */
  @Prop({default:'2'}) public precision?:string;

  /**
   * 传入数据
   *
   * @type {*}
   * @memberof AppFormatData
   */
  @Prop() public data!:any;

  /**
   * 显示值
   *
   * @memberof AppFormatData
   */
  getcurValue(){
    if(this.data){
      if(Object.is(this.dataType,"DECIMAL") || Object.is(this.dataType,"FLOAT") || Object.is(this.dataType,"CURRENCY")){
        let number = Number(this.data);
        let precision = Number(this.precision);
        if(Object.is(number,NaN)){
          return this.data;
        }else{
          let result = "";
          if(Object.is(this.dataType,"CURRENCY")){
              result = Number(number.toFixed((Object.is(precision,NaN) ? 2 : precision))).toLocaleString('en-US');
          }else{
              result = number.toFixed((Object.is(precision,NaN) ? 2 : precision));
          }
          let index = result.indexOf(".");
          let fornum = (Object.is(precision,NaN) ? 2 : precision) - result.length + index + 1;
          if(Object.is(index,-1) && !Object.is(precision,0)){
            result += ".";
          }
          for (let i = 0; i < fornum; i++) {
            result += '0';
            
          }
          return result;
        } 
      } else if (this.format){
        if(this.format.indexOf('%1$t') !== -1){
          return moment(this.data).format("YYYY-MM-DD HH:mm:ss");
        }else{
          return moment(this.data).format(this.format);
        }
      }else{
        return this.data;
      }
    }else{
      return "";
    }
  }

}
</script>
<style lang="less">
@import './app-format-data.less';
</style>