index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. Component({
  2. externalClasses: ['wr-class', 'symbol-class', 'decimal-class'],
  3. useStore: [],
  4. properties: {
  5. priceUnit: {
  6. type: String,
  7. value: 'fen',
  8. }, // 价格单位,分 | 元, fen,yuan
  9. price: {
  10. type: null,
  11. value: '',
  12. observer(price) {
  13. this.format(price);
  14. },
  15. }, // 价格, 以分为单位
  16. type: {
  17. type: String,
  18. value: '', //
  19. }, // main 粗体, lighter 细体, mini 黑色, del 中划线, delthrough 中划线,包括货币符号
  20. symbol: {
  21. type: String,
  22. value: '¥', // '¥',
  23. }, // 货币符号,默认是人民币符号¥
  24. fill: Boolean, // 是否自动补齐两位小数
  25. decimalSmaller: Boolean, // 小数字号小一点
  26. lineThroughWidth: {
  27. type: null,
  28. value: '0.12em',
  29. }, // 划线价线条高度
  30. },
  31. data: {
  32. pArr: [],
  33. },
  34. methods: {
  35. format(price) {
  36. price = parseFloat(`${price}`);
  37. const pArr = [];
  38. if (!isNaN(price)) {
  39. const isMinus = price < 0;
  40. if (isMinus) {
  41. price = -price;
  42. }
  43. if (this.properties.priceUnit === 'yuan') {
  44. const priceSplit = price.toString().split('.');
  45. pArr[0] = priceSplit[0];
  46. pArr[1] = !priceSplit[1]
  47. ? '00'
  48. : priceSplit[1].length === 1
  49. ? `${priceSplit[1]}0`
  50. : priceSplit[1];
  51. } else {
  52. price = Math.round(price * 10 ** 8) / 10 ** 8; // 恢复精度丢失
  53. price = Math.ceil(price); // 向上取整
  54. pArr[0] = price >= 100 ? `${price}`.slice(0, -2) : '0';
  55. pArr[1] = `${price + 100}`.slice(-2);
  56. }
  57. if (!this.properties.fill) {
  58. // 如果 fill 为 false, 不显示小数末尾的0
  59. if (pArr[1] === '00') pArr[1] = '';
  60. else if (pArr[1][1] === '0') pArr[1] = pArr[1][0];
  61. }
  62. if (isMinus) {
  63. pArr[0] = `-${pArr[0]}`;
  64. }
  65. }
  66. this.setData({ pArr });
  67. },
  68. },
  69. });