UNPKG

2.02 kBPlain TextView Raw
1<script>
2export default {
3 name: 'ElAvatar',
4
5 props: {
6 size: {
7 type: [Number, String],
8 validator(val) {
9 if (typeof val === 'string') {
10 return ['large', 'medium', 'small'].includes(val);
11 }
12 return typeof val === 'number';
13 }
14 },
15 shape: {
16 type: String,
17 default: 'circle',
18 validator(val) {
19 return ['circle', 'square'].includes(val);
20 }
21 },
22 icon: String,
23 src: String,
24 alt: String,
25 srcSet: String,
26 error: Function,
27 fit: {
28 type: String,
29 default: 'cover'
30 }
31 },
32
33 data() {
34 return {
35 isImageExist: true
36 };
37 },
38
39 computed: {
40 avatarClass() {
41 const { size, icon, shape } = this;
42 let classList = ['el-avatar'];
43
44 if (size && typeof size === 'string') {
45 classList.push(`el-avatar--${size}`);
46 }
47
48 if (icon) {
49 classList.push('el-avatar--icon');
50 }
51
52 if (shape) {
53 classList.push(`el-avatar--${shape}`);
54 }
55
56 return classList.join(' ');
57 }
58 },
59
60 methods: {
61 handleError() {
62 const { error } = this;
63 const errorFlag = error ? error() : undefined;
64 if (errorFlag !== false) {
65 this.isImageExist = false;
66 }
67 },
68 renderAvatar() {
69 const { icon, src, alt, isImageExist, srcSet, fit } = this;
70
71 if (isImageExist && src) {
72 return <img
73 src={src}
74 onError={this.handleError}
75 alt={alt}
76 srcSet={srcSet}
77 style={{ 'object-fit': fit }}/>;
78 }
79
80 if (icon) {
81 return (<i class={icon} />);
82 }
83
84 return this.$slots.default;
85 }
86 },
87
88 render() {
89 const { avatarClass, size } = this;
90
91 const sizeStyle = typeof size === 'number' ? {
92 height: `${size}px`,
93 width: `${size}px`,
94 lineHeight: `${size}px`
95 } : {};
96
97 return (
98 <span class={ avatarClass } style={ sizeStyle }>
99 {
100 this.renderAvatar()
101 }
102 </span>
103 );
104 }
105
106};
107</script>