index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import baseComponent from '../helpers/baseComponent'
  2. import classNames from '../helpers/classNames'
  3. import styleToCssString from '../helpers/styleToCssString'
  4. baseComponent({
  5. properties: {
  6. prefixCls: {
  7. type: String,
  8. value: 'wux-avatar',
  9. },
  10. shape: {
  11. type: String,
  12. value: 'circle',
  13. },
  14. size: {
  15. type: String,
  16. value: 'default',
  17. },
  18. src: {
  19. type: String,
  20. value: '',
  21. },
  22. bodyStyle: {
  23. type: [String, Object],
  24. value: '',
  25. observer(newVal) {
  26. this.setData({
  27. extStyle: styleToCssString(newVal),
  28. })
  29. },
  30. },
  31. scale: {
  32. type: Boolean,
  33. value: false,
  34. },
  35. },
  36. data: {
  37. extStyle: '',
  38. childrenStyle: '',
  39. },
  40. computed: {
  41. classes() {
  42. const { prefixCls, shape, size, src } = this.data
  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. const query = wx.createSelectorQuery().in(this)
  59. query.select(`.${prefixCls}`).boundingClientRect()
  60. query.select(`.${prefixCls}__string`).boundingClientRect()
  61. query.exec((rects) => {
  62. if (rects.filter((n) => !n).length) return
  63. const [parent, child] = rects
  64. const offset = parent.width - 8 < child.width
  65. const childrenScale = offset ? (parent.width - 8) / child.width : 1
  66. const childrenStyle = childrenScale !== 1 ? `position: absolute; display: inline-block; transform: scale(${childrenScale}); left: calc(50% - ${Math.round(child.width / 2)}px)` : ''
  67. this.setData({
  68. childrenStyle,
  69. })
  70. })
  71. },
  72. },
  73. ready() {
  74. if (!this.data.src && this.data.scale) {
  75. this.setScale()
  76. }
  77. },
  78. })