index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import utils from '@/common/utils';
  2. const { ztMoment } = utils;
  3. import iconMap from '../../config/btn-icon-config';
  4. function pluralize(time, label) {
  5. if (time === 1) {
  6. return time + label;
  7. }
  8. return time + label + 's';
  9. }
  10. export function timeAgo(time) {
  11. const between = Date.now() / 1000 - Number(time);
  12. if (between < 3600) {
  13. return pluralize(~~(between / 60), ' minute');
  14. } else if (between < 86400) {
  15. return pluralize(~~(between / 3600), ' hour');
  16. } else {
  17. return pluralize(~~(between / 86400), ' day');
  18. }
  19. }
  20. /* 数字 格式化*/
  21. export function numberFormatter(num, digits) {
  22. const si = [
  23. { value: 1e18, symbol: 'E' },
  24. { value: 1e15, symbol: 'P' },
  25. { value: 1e12, symbol: 'T' },
  26. { value: 1e9, symbol: 'G' },
  27. { value: 1e6, symbol: 'M' },
  28. { value: 1e3, symbol: 'k' }
  29. ];
  30. for (let i = 0; i < si.length; i++) {
  31. if (num >= si[i].value) {
  32. return (num / si[i].value + 0.1).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol;
  33. }
  34. }
  35. return num.toString();
  36. }
  37. export function toThousandFilter(num) {
  38. return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','));
  39. }
  40. export function dateFormatter(value, fmt) {
  41. if (value) {
  42. return ztMoment(value).format(fmt || 'YYYY-MM-DD');
  43. } else {
  44. return '';
  45. }
  46. }
  47. // 操作按钮图标
  48. export function optIcon(type, defaultIcon) {
  49. if (defaultIcon) {
  50. return defaultIcon;
  51. }
  52. let icon = '';
  53. for (const item of iconMap) {
  54. const texts = item[0].split(',').map(ele => ele.trim());
  55. if (texts.includes(type)) {
  56. icon = item[1];
  57. break;
  58. }
  59. }
  60. // const icon = iconMap.get(type);
  61. return icon ? icon : 'el-icon-edit';
  62. }
  63. const install = function(Vue) {
  64. let filters = { pluralize, timeAgo, numberFormatter, toThousandFilter, dateFormatter, optIcon };
  65. Object.keys(filters).forEach(key => {
  66. Vue.filter(key, filters[key]);
  67. });
  68. };
  69. /* istanbul ignore if */
  70. if (typeof window !== 'undefined' && window.Vue) {
  71. install(window.Vue);
  72. }
  73. export default {
  74. version: '1.0.0',
  75. install
  76. };