ant-design-vue/components/avatar/Avatar.vue

100 lines
2.2 KiB
Vue
Raw Normal View History

2017-11-09 10:57:34 +00:00
<template>
2017-11-10 02:28:49 +00:00
<span :class="classes" :style="styles">
2017-11-09 10:57:34 +00:00
<img v-if="src" :src="src"/>
<icon v-else-if="icon" :type="icon" />
<span
v-else
ref="avatorChildren"
:class="[prefixCls+'-string']"
:style="childrenStyle">
<slot></slot>
</span>
</span>
</template>
<script>
2017-11-10 02:28:49 +00:00
import Icon from '../icon'
2017-11-09 10:57:34 +00:00
export default {
name: 'Avatar',
props: {
prefixCls: {
type: String,
default: 'ant-avatar',
},
shape: {
2017-11-10 02:28:49 +00:00
validator: (val) => (['circle', 'square'].includes(val)),
2017-11-09 10:57:34 +00:00
default: 'circle',
},
size: {
2017-11-10 02:28:49 +00:00
validator: (val) => (['small', 'large', 'default'].includes(val)),
2017-11-09 10:57:34 +00:00
default: 'default',
},
2017-11-10 02:28:49 +00:00
styles: {
2017-11-09 10:57:34 +00:00
type: Object,
2017-11-10 02:28:49 +00:00
default: () => ({}),
2017-11-09 10:57:34 +00:00
},
2017-11-10 02:28:49 +00:00
src: String,
icon: String,
2017-11-09 10:57:34 +00:00
},
data () {
return {
2017-11-10 02:28:49 +00:00
isExistSlot: false,
2017-11-09 10:57:34 +00:00
scale: 1,
}
},
computed: {
classes () {
const { prefixCls, shape, size, src, icon } = this
return {
[`${prefixCls}`]: true,
2017-11-10 02:28:49 +00:00
[`${prefixCls}-image`]: !!src,
[`${prefixCls}-icon`]: !!icon,
2017-11-09 10:57:34 +00:00
[`${prefixCls}-${shape}`]: true,
[`${prefixCls}-lg`]: size === 'large',
[`${prefixCls}-sm`]: size === 'small',
}
},
childrenStyle () {
const children = this.$refs.avatorChildren
let style = {}
2017-11-10 02:28:49 +00:00
if (this.isExistSlot) {
2017-11-09 10:57:34 +00:00
style = {
msTransform: `scale(${this.scale})`,
WebkitTransform: `scale(${this.scale})`,
transform: `scale(${this.scale})`,
position: 'absolute',
2017-11-10 02:28:49 +00:00
// display: 'inline-block',
2017-11-09 10:57:34 +00:00
left: `calc(50% - ${Math.round(children.offsetWidth / 2)}px)`,
}
}
return style
},
},
methods: {
setScale () {
2017-11-10 02:28:49 +00:00
const { src, icon, $refs, $el } = this
const children = $refs.avatorChildren
this.isExistSlot = !src && !icon
2017-11-09 10:57:34 +00:00
if (children) {
const childrenWidth = children.offsetWidth
2017-11-10 02:28:49 +00:00
const avatarWidth = $el.getBoundingClientRect().width
2017-11-09 10:57:34 +00:00
if (avatarWidth - 8 < childrenWidth) {
this.scale = (avatarWidth - 8) / childrenWidth
} else {
this.scale = 1
}
}
},
},
mounted () {
this.setScale()
},
updated () {
this.setScale()
},
components: {
Icon,
},
}
</script>