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