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

101 lines
2.2 KiB
Vue
Raw Normal View History

2017-11-09 18:57:34 +08:00
<template>
2018-01-26 13:48:20 +08:00
<span :class="classes">
2017-11-09 18:57:34 +08: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 10:28:49 +08:00
import Icon from '../icon'
2017-11-09 18:57:34 +08:00
export default {
name: 'Avatar',
props: {
prefixCls: {
type: String,
default: 'ant-avatar',
},
shape: {
2017-11-10 10:28:49 +08:00
validator: (val) => (['circle', 'square'].includes(val)),
2017-11-09 18:57:34 +08:00
default: 'circle',
},
size: {
2017-11-10 10:28:49 +08:00
validator: (val) => (['small', 'large', 'default'].includes(val)),
2017-11-09 18:57:34 +08:00
default: 'default',
},
2017-11-10 10:28:49 +08:00
src: String,
icon: String,
2017-11-09 18:57:34 +08:00
},
data () {
return {
2017-11-10 10:28:49 +08:00
isExistSlot: false,
2017-11-09 18:57:34 +08:00
scale: 1,
2017-12-20 10:56:21 +08:00
childrenWidth: 0,
2017-11-09 18:57:34 +08:00
}
},
computed: {
classes () {
const { prefixCls, shape, size, src, icon } = this
return {
[`${prefixCls}`]: true,
2017-11-10 10:28:49 +08:00
[`${prefixCls}-image`]: !!src,
[`${prefixCls}-icon`]: !!icon,
2017-11-09 18:57:34 +08:00
[`${prefixCls}-${shape}`]: true,
[`${prefixCls}-lg`]: size === 'large',
[`${prefixCls}-sm`]: size === 'small',
}
},
childrenStyle () {
let style = {}
2017-12-20 10:56:21 +08:00
const { scale, isExistSlot, childrenWidth } = this
if (isExistSlot) {
2017-11-09 18:57:34 +08:00
style = {
2017-12-20 10:56:21 +08:00
msTransform: `scale(${scale})`,
WebkitTransform: `scale(${scale})`,
transform: `scale(${scale})`,
2017-11-09 18:57:34 +08:00
position: 'absolute',
2017-12-20 10:56:21 +08:00
display: 'inline-block',
left: `calc(50% - ${Math.round(childrenWidth / 2)}px)`,
2017-11-09 18:57:34 +08:00
}
}
return style
},
},
methods: {
setScale () {
2017-11-10 10:28:49 +08:00
const { src, icon, $refs, $el } = this
const children = $refs.avatorChildren
this.isExistSlot = !src && !icon
2017-11-09 18:57:34 +08:00
if (children) {
2017-12-20 10:56:21 +08:00
this.childrenWidth = children.offsetWidth
2017-11-10 10:28:49 +08:00
const avatarWidth = $el.getBoundingClientRect().width
2017-12-20 10:56:21 +08:00
if (avatarWidth - 8 < this.childrenWidth) {
this.scale = (avatarWidth - 8) / this.childrenWidth
2017-11-09 18:57:34 +08:00
} else {
this.scale = 1
}
}
},
},
mounted () {
2018-02-02 17:42:05 +08:00
this.$nextTick(() => {
this.setScale()
})
2017-11-09 18:57:34 +08:00
},
updated () {
2018-02-02 17:42:05 +08:00
this.$nextTick(() => {
this.setScale()
})
2017-11-09 18:57:34 +08:00
},
components: {
Icon,
},
}
</script>