iview/src/components/avatar/avatar.vue

102 lines
3.2 KiB
Vue
Raw Normal View History

2017-08-15 14:52:56 +08:00
<template>
<span :class="classes">
<img :src="src" v-if="src">
2018-07-03 17:37:22 +08:00
<Icon :type="icon" :custom="customIcon" v-else-if="icon || customIcon"></Icon>
2017-08-15 14:52:56 +08:00
<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']);
},
2018-06-28 15:00:09 +08:00
default () {
2018-08-07 16:35:27 +08:00
return !this.$IVIEW || this.$IVIEW.size === '' ? 'default' : this.$IVIEW.size;
2018-06-28 15:00:09 +08:00
}
2017-08-15 11:03:20 +08:00
},
src: {
type: String
},
icon: {
type: String
2018-07-03 17:37:22 +08:00
},
customIcon: {
type: String,
default: ''
},
2017-08-15 10:07:15 +08:00
},
2017-08-15 14:52:56 +08:00
data () {
return {
prefixCls: prefixCls,
scale: 1,
childrenWidth: 0,
2017-08-15 14:52:56 +08:00
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,
2018-07-03 17:37:22 +08:00
[`${prefixCls}-icon`]: !!this.icon || !!this.customIcon
2017-08-15 11:03:20 +08:00
}
];
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.childrenWidth / 2)}px)`
2017-08-15 14:52:56 +08:00
};
}
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.$refs.children) {
// set children width again to make slot centered
this.childrenWidth = this.$refs.children.offsetWidth;
2017-08-15 14:52:56 +08:00
const avatarWidth = this.$el.getBoundingClientRect().width;
// add 4px gap for each side to get better performance
if (avatarWidth - 8 < this.childrenWidth) {
this.scale = (avatarWidth - 8) / this.childrenWidth;
2017-08-15 14:52:56 +08:00
} 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>