-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathAvatar.vue
92 lines (90 loc) · 1.99 KB
/
Avatar.vue
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
<template>
<div :style="style" class="avatar">
<table>
<tbody>
<tr>
<td v-if="!hasImage">
{{ initials }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
name: 'Avatar',
props: {
fullname: { type: String, default: '' },
size: { type: Number, default: 48 },
radius: {
type: Number,
default: 50,
validator: value => value >= 0 && value <= 50
},
color: { type: String, default: '' },
image: { type: String, default: '' }
},
computed: {
initials () {
const words = this.fullname.split(/[\s-]+/)
return words.map(word => word.substr(0, 1)).join('').substr(0, 3).toUpperCase()
},
style () {
const fontSize = this.initials.length > 2 ? this.size / 3 : this.size / 2
return {
width: this.size + 'px',
height: this.size + 'px',
'border-radius': this.radius + '%',
'font-size': fontSize + 'px',
'background-color':
this.color === '' ? this.toColor(this.fullname) : this.color,
'background-image': this.hasImage ? 'url(' + this.image + ')' : 'none'
}
},
hasImage () {
return this.image !== ''
}
},
methods: {
toColor (str) {
let hash = 0
if (!str) return 'black'
for (const char of str.split('')) {
hash = (hash << (8 - hash)) + char.charCodeAt(0)
}
return '#' + Math.abs(hash).toString(16).substr(0, 6)
}
}
}
</script>
<style scoped>
.avatar {
display: inline-block;
background-color: black;
color: white;
width: 48px;
height: 48px;
font-size: 12px;
border-radius: 50%;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-image: none;
}
.avatar table {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
border-spacing: 0;
}
.avatar table td {
text-align: center;
vertical-align: middle;
}
.avatar img {
width: 100%;
overflow: hidden;
}
</style>