index.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import baseComponent from '../helpers/baseComponent'
  2. import classNames from '../helpers/libs/classNames'
  3. import styleToCssString from '../helpers/libs/styleToCssString'
  4. import { useRect } from '../helpers/hooks/useDOM'
  5. baseComponent({
  6. properties: {
  7. prefixCls: {
  8. type: String,
  9. value: 'wux-avatar',
  10. },
  11. shape: {
  12. type: String,
  13. value: 'circle',
  14. },
  15. size: {
  16. type: String,
  17. value: 'default',
  18. },
  19. src: {
  20. type: String,
  21. value: '',
  22. },
  23. bodyStyle: {
  24. type: [String, Object],
  25. value: '',
  26. observer(newVal) {
  27. this.setData({
  28. extStyle: styleToCssString(newVal),
  29. })
  30. },
  31. },
  32. scale: {
  33. type: Boolean,
  34. value: false,
  35. },
  36. },
  37. data: {
  38. extStyle: '',
  39. childrenStyle: '',
  40. },
  41. computed: {
  42. classes: ['prefixCls, shape, size, src', function(prefixCls, shape, size, src) {
  43. const wrap = classNames(prefixCls, {
  44. [`${prefixCls}--${shape}`]: shape,
  45. [`${prefixCls}--${size}`]: size,
  46. [`${prefixCls}--thumb`]: src,
  47. })
  48. const string = `${prefixCls}__string`
  49. return {
  50. wrap,
  51. string,
  52. }
  53. }],
  54. },
  55. methods: {
  56. setScale() {
  57. const { prefixCls } = this.data
  58. useRect([`.${prefixCls}`, `.${prefixCls}__string`], this)
  59. .then(([parent, child]) => {
  60. const offset = parent.width - 8 < child.width
  61. const childrenScale = offset ? (parent.width - 8) / child.width : 1
  62. const childrenStyle = childrenScale !== 1
  63. ? styleToCssString({
  64. position: 'absolute',
  65. display: 'inline-block',
  66. transform: `scale(${childrenScale})`,
  67. left: `calc(50% - ${Math.round(child.width / 2)}px)`,
  68. })
  69. : ''
  70. this.setData({
  71. childrenStyle,
  72. })
  73. })
  74. },
  75. },
  76. ready() {
  77. if (!this.data.src && this.data.scale) {
  78. this.setScale()
  79. }
  80. },
  81. })