wk-avatar.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. <template>
  2. <view
  3. :id="id"
  4. :style="[boxStyle]"
  5. class="wk-avatar"
  6. @click="handleClick">
  7. <template v-if="avatar">
  8. <wk-auth-img
  9. :src="avatar"
  10. :preview="preview"
  11. class="wk-avatar-pic"
  12. @load="handleLoad"
  13. @error="handleError" />
  14. </template>
  15. <template v-else>
  16. <text :style="{fontSize: size + 'px'}" class="text">
  17. {{ nameStr }}
  18. </text>
  19. </template>
  20. </view>
  21. </template>
  22. <script>
  23. import {
  24. guid,
  25. unitToPx
  26. } from '@/utils/lib.js'
  27. export default {
  28. name: 'WkAvatar',
  29. props: {
  30. name: { // 用户名
  31. type: String,
  32. default: ''
  33. },
  34. size: { // 无头像图时用户名字体大小
  35. type: Number,
  36. default: 16
  37. },
  38. avatar: { // 头像图
  39. type: String,
  40. default: null
  41. },
  42. preview: { // 头像是否允许点击查看大图
  43. type: Boolean,
  44. default: true
  45. },
  46. width: { // 容器宽
  47. type: [String, Number],
  48. default: null
  49. },
  50. height: { // 容器高
  51. type: [String, Number],
  52. default: null
  53. },
  54. customerStyle: { // 容器样式
  55. type: Object,
  56. default: () => {}
  57. }
  58. },
  59. data() {
  60. return {
  61. id: guid(),
  62. pixelRatio: 1,
  63. bgColor: '#3E84E9'
  64. }
  65. },
  66. computed: {
  67. nameStr() {
  68. if (!this.name) return ''
  69. return this.name.length > 2 ? this.name.slice(-2) : this.name
  70. },
  71. boxStyle() {
  72. const obj = {
  73. ...this.customerStyle,
  74. backgroundColor: this.bgColor
  75. }
  76. if (this.width) {
  77. obj.width = unitToPx(this.width)
  78. }
  79. if (this.height) {
  80. obj.height = unitToPx(this.height)
  81. }
  82. return obj
  83. }
  84. },
  85. methods: {
  86. handleClick(evt) {
  87. this.$emit('click', evt)
  88. },
  89. handleLoad() {
  90. this.bgColor = 'unset'
  91. },
  92. handleError() {
  93. this.bgColor = '#3E84E9'
  94. }
  95. }
  96. }
  97. </script>
  98. <style scoped lang="scss">
  99. .wk-avatar {
  100. width: 100%;
  101. height: 100%;
  102. border-radius: 50%;
  103. overflow: hidden;
  104. background-color: #3E84E9;
  105. @include center;
  106. .text {
  107. line-height: 1;
  108. font-size: 28rpx;
  109. color: white;
  110. vertical-align: middle;
  111. }
  112. .wk-avatar-pic {
  113. width: 100%;
  114. height: 100%;
  115. border-radius: 50%;
  116. display: block;
  117. }
  118. }
  119. </style>