cl-avatar.vue 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <template>
  2. <view :class="['cl-avatar', isShape]" :style="{ height, width, backgroundColor }">
  3. <slot v-if="$slots.default || $slots.$default"> </slot>
  4. <template v-else>
  5. <slot name="placeholder" v-if="!src">
  6. <view class="cl-avatar__placeholder">
  7. <text class="cl-icon-my" :style="{ fontSize }"></text>
  8. </view>
  9. </slot>
  10. <slot name="error" v-else-if="isError">
  11. <view class="cl-avatar__error"> Error </view>
  12. </slot>
  13. <image
  14. v-else
  15. class="cl-avatar__target"
  16. :src="src"
  17. :mode="mode"
  18. :lazy-load="lazyLoad"
  19. @error="handleError"
  20. @load="handleLoad"
  21. ></image>
  22. </template>
  23. </view>
  24. </template>
  25. <script>
  26. /**
  27. * avatar 头像
  28. * @description 头像
  29. * @tutorial https://docs.cool-js.com/uni/components/view/avatar.html
  30. * @property {String} src 图片链接
  31. * @property {Number} size 头像大小,默认80
  32. * @property {String} shape 头像的形状,默认circle
  33. * @property {String} mode 裁剪,缩放模式
  34. * @example <cl-avatar src="http://" />
  35. */
  36. export default {
  37. name: "cl-avatar",
  38. props: {
  39. // 图片链接
  40. src: String,
  41. // 懒加载
  42. lazyLoad: Boolean,
  43. // 头像大小
  44. size: {
  45. type: Number,
  46. default: 80,
  47. },
  48. // 头像的形状 circle | square
  49. shape: {
  50. type: String,
  51. default: "circle",
  52. },
  53. // 裁剪,缩放模式
  54. mode: {
  55. type: String,
  56. default: "scaleToFill",
  57. },
  58. },
  59. data() {
  60. return {
  61. isError: false,
  62. };
  63. },
  64. computed: {
  65. isShape() {
  66. return `cl-avatar--${this.shape}`;
  67. },
  68. height() {
  69. return this.size + "rpx";
  70. },
  71. width() {
  72. return this.size + "rpx";
  73. },
  74. fontSize() {
  75. return this.size / 1.7 + "rpx";
  76. },
  77. backgroundColor() {
  78. return this.src ? "" : "#c0c4cc";
  79. },
  80. },
  81. methods: {
  82. handleLoad(e) {
  83. this.isError = false;
  84. this.$emit("error", e);
  85. },
  86. handleError(e) {
  87. this.isError = true;
  88. this.$emit("load", e);
  89. },
  90. },
  91. };
  92. </script>