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

100 lines
2.3 KiB
React
Raw Normal View History

2018-03-19 02:16:27 +00:00
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
src: String,
icon: String,
2017-11-09 10:57:34 +00:00
},
data () {
2018-02-22 07:09:03 +00:00
this.isExistSlot = false
this.childrenWidth = 0
2017-11-09 10:57:34 +00:00
return {
scale: 1,
}
},
computed: {
classes () {
const { prefixCls, shape, size, src, icon } = this
return {
[`${prefixCls}`]: true,
2018-02-22 07:13:41 +00:00
[`${prefixCls}-image`]: !!src,
2017-11-10 02:28:49 +00:00
[`${prefixCls}-icon`]: !!icon,
2017-11-09 10:57:34 +00:00
[`${prefixCls}-${shape}`]: true,
[`${prefixCls}-lg`]: size === 'large',
[`${prefixCls}-sm`]: size === 'small',
}
},
childrenStyle () {
let style = {}
2017-12-20 02:56:21 +00:00
const { scale, isExistSlot, childrenWidth } = this
if (isExistSlot) {
2017-11-09 10:57:34 +00:00
style = {
2017-12-20 02:56:21 +00:00
msTransform: `scale(${scale})`,
WebkitTransform: `scale(${scale})`,
transform: `scale(${scale})`,
2017-11-09 10:57:34 +00:00
position: 'absolute',
2017-12-20 02:56:21 +00:00
display: 'inline-block',
left: `calc(50% - ${Math.round(childrenWidth / 2)}px)`,
2017-11-09 10:57:34 +00:00
}
}
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) {
2017-12-20 02:56:21 +00:00
this.childrenWidth = children.offsetWidth
2017-11-10 02:28:49 +00:00
const avatarWidth = $el.getBoundingClientRect().width
2017-12-20 02:56:21 +00:00
if (avatarWidth - 8 < this.childrenWidth) {
this.scale = (avatarWidth - 8) / this.childrenWidth
2017-11-09 10:57:34 +00:00
} else {
this.scale = 1
}
}
},
},
mounted () {
2018-02-02 09:42:05 +00:00
this.$nextTick(() => {
this.setScale()
})
2017-11-09 10:57:34 +00:00
},
updated () {
2018-02-02 09:42:05 +00:00
this.$nextTick(() => {
this.setScale()
})
2017-11-09 10:57:34 +00:00
},
2018-03-19 01:43:31 +00:00
render () {
const { classes, prefixCls, src, icon, childrenStyle, $slots } = this
return (
<span class={classes}>
{src ? <img src={src}/>
2018-03-19 02:16:27 +00:00
: (icon ? <Icon type={icon} />
2018-03-19 01:43:31 +00:00
: <span
ref='avatorChildren'
class={prefixCls + '-string'}
style={childrenStyle}>
{$slots.default}
</span>) }
</span>
)
2017-11-09 10:57:34 +00:00
},
}
2018-03-19 02:16:27 +00:00