본문으로 바로가기

728x90

이번 포스트에서는 3자리마다 쉼표 찍는 방법과 bytes 길이를 자동으로 표시하는 Vue.js의 필터에 대해서 설명합니다.

 

3자리마다 쉼표찍기

/main.js에 아래의 코드를 삽입합니다.

Vue.filter('currency', function (num) {
    // jacked from: https://github.com/sindresorhus/pretty-bytes
    if (typeof num !== 'number' || isNaN(num)) {
      throw new TypeError('Expected a number');
    }
    return num.toFixed(0).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")
});

사용방법

{{ updateTotalBytes | currency }}

Bytes 길이 자동 표시

/main.js에 아래의 코드를 삽입합니다.

Vue.filter('prettyBytes', function (num) {
    // jacked from: https://github.com/sindresorhus/pretty-bytes
    if (typeof num !== 'number' || isNaN(num)) {
      throw new TypeError('Expected a number');
    }
  
    var exponent;
    var unit;
    var neg = num < 0;
    var units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  
    if (neg) {
      num = -num;
    }
  
    if (num < 1) {
      return (neg ? '-' : '') + num + ' B';
    }
  
    exponent = Math.min(Math.floor(Math.log(num) / Math.log(1000)), units.length - 1);
    num = (num / Math.pow(1000, exponent)).toFixed(2) * 1;
    unit = units[exponent];
  
    return (neg ? '-' : '') + num + ' ' + unit;
});

사용방법

{{ updateDownloadBytes | prettyBytes }} / {{ updateTotalBytes | prettyBytes }}

사용 예시

아래의 그림에서 다운로드 중인 상태를 예쁘게 표시할 수 있습니다.

Bytes 길이 자동표시

 

참고 주소

https://gist.github.com/james2doyle/4aba55c22f084800c199

 

 

728x90