效果展示:
传递三个参数:
- name:要显示的名称;
- size:头像的大小;
- cutNum:分割当前名称的最后几位数;
代码如下:
<template>
<div
:style="{
color: '#fff',
borderRadius: '50%',
width: size + 'px',
height: size + 'px',
display: 'block',
textAlign: 'center',
lineHeight: size + 'px',
fontSize: size * 0.4 + 'px',
background: color(name)
}"
>
{{ name.slice(-cutNum) }}
</div>
</template>
<script lang="ts" setup>
defineProps({
name: {
type: String,
default: ""
},
size: {
type: Number,
default: 16
},
cutNum: {
type: Number,
default: 1
}
});
const color = (name: string) => {
if (name) {
let num = "";
for (let i = 0; i < name.length; i++) {
num += name[i].charCodeAt(0).toString();
}
const r = Math.min(100 + (parseInt(num.slice(0, 2), 10) % 55), 255);
const g = Math.min(100 + (parseInt(num.slice(2, 4), 10) % 55), 255);
const b = Math.min(100 + (parseInt(num.slice(4, 6), 10) % 55), 255);
return `rgb(${r}, ${g}, ${b})`;
} else {
return "rgb(125, 125, 125)";
}
};
</script>
使用代码如下:
<AuthorImage name="铁甲小宝" :size="74" :cut-num="2"></AuthorImage>