2017-08-15 14:52:56 +08:00
|
|
|
<template>
|
|
|
|
<span :class="classes">
|
|
|
|
<img :src="src" v-if="src">
|
|
|
|
<Icon :type="icon" v-else-if="icon"></Icon>
|
|
|
|
<span ref="children" :class="[prefixCls + '-string']" :style="childrenStyle" v-else><slot></slot></span>
|
|
|
|
</span>
|
|
|
|
</template>
|
2017-08-15 10:07:15 +08:00
|
|
|
<script>
|
2017-08-15 11:03:20 +08:00
|
|
|
import Icon from '../icon';
|
|
|
|
import { oneOf } from '../../utils/assist';
|
|
|
|
|
2017-08-15 10:07:15 +08:00
|
|
|
const prefixCls = 'ivu-avatar';
|
|
|
|
|
|
|
|
export default {
|
|
|
|
name: 'Avatar',
|
2017-08-15 14:52:56 +08:00
|
|
|
components: { Icon },
|
2017-08-15 10:07:15 +08:00
|
|
|
props: {
|
2017-08-15 11:03:20 +08:00
|
|
|
shape: {
|
|
|
|
validator (value) {
|
|
|
|
return oneOf(value, ['circle', 'square']);
|
|
|
|
},
|
|
|
|
default: 'circle'
|
|
|
|
},
|
|
|
|
size: {
|
|
|
|
validator (value) {
|
|
|
|
return oneOf(value, ['small', 'large', 'default']);
|
|
|
|
},
|
|
|
|
default: 'default'
|
|
|
|
},
|
|
|
|
src: {
|
|
|
|
type: String
|
|
|
|
},
|
|
|
|
icon: {
|
|
|
|
type: String
|
|
|
|
}
|
2017-08-15 10:07:15 +08:00
|
|
|
},
|
2017-08-15 14:52:56 +08:00
|
|
|
data () {
|
|
|
|
return {
|
|
|
|
prefixCls: prefixCls,
|
|
|
|
scale: 1,
|
|
|
|
isSlotShow: false
|
|
|
|
};
|
|
|
|
},
|
2017-08-15 10:07:15 +08:00
|
|
|
computed: {
|
2017-08-15 11:03:20 +08:00
|
|
|
classes () {
|
|
|
|
return [
|
|
|
|
`${prefixCls}`,
|
|
|
|
`${prefixCls}-${this.shape}`,
|
|
|
|
`${prefixCls}-${this.size}`,
|
|
|
|
{
|
|
|
|
[`${prefixCls}-image`]: !!this.src,
|
|
|
|
[`${prefixCls}-icon`]: !!this.icon
|
|
|
|
}
|
|
|
|
];
|
2017-08-15 14:52:56 +08:00
|
|
|
},
|
|
|
|
childrenStyle () {
|
|
|
|
let style = {};
|
|
|
|
if (this.isSlotShow) {
|
|
|
|
style = {
|
|
|
|
msTransform: `scale(${this.scale})`,
|
|
|
|
WebkitTransform: `scale(${this.scale})`,
|
|
|
|
transform: `scale(${this.scale})`,
|
|
|
|
position: 'absolute',
|
|
|
|
display: 'inline-block',
|
|
|
|
left: `calc(50% - ${Math.round(this.$refs.children.offsetWidth / 2)}px)`
|
|
|
|
};
|
|
|
|
}
|
|
|
|
return style;
|
2017-08-15 11:03:20 +08:00
|
|
|
}
|
2017-08-15 10:07:15 +08:00
|
|
|
},
|
2017-08-15 14:52:56 +08:00
|
|
|
methods: {
|
|
|
|
setScale () {
|
|
|
|
this.isSlotShow = !this.src && !this.icon;
|
|
|
|
if (this.$slots.default) {
|
|
|
|
const childrenWidth = this.$refs.children.offsetWidth;
|
|
|
|
const avatarWidth = this.$el.getBoundingClientRect().width;
|
|
|
|
// add 4px gap for each side to get better performance
|
|
|
|
if (avatarWidth - 8 < childrenWidth) {
|
|
|
|
this.scale = (avatarWidth - 8) / childrenWidth;
|
|
|
|
} else {
|
|
|
|
this.scale = 1;
|
2017-08-15 11:23:52 +08:00
|
|
|
}
|
2017-08-15 14:52:56 +08:00
|
|
|
}
|
2017-08-15 11:23:52 +08:00
|
|
|
}
|
2017-08-15 14:52:56 +08:00
|
|
|
},
|
|
|
|
mounted () {
|
|
|
|
this.setScale();
|
|
|
|
},
|
|
|
|
updated () {
|
|
|
|
this.setScale();
|
2017-08-15 10:07:15 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
</script>
|