feat(Badge): add offset prop (#7977)

This commit is contained in:
neverland 2021-01-23 16:56:44 +08:00 committed by GitHub
commit 7a73392895
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 49 additions and 2 deletions

View File

@ -117,6 +117,7 @@ Use `content` slot to custom :content of badge.
| color | Background color | _string_ | `#ee0a24` |
| dot | Whether to show dot | _boolean_ | `false` |
| max | Max valueshow `{max}+` when exceedonly works when content is number | _number \| string_ | - |
| offset `v3.0.5` | Offset of badge dot | _[number, number]_ | - |
### Slots

View File

@ -129,6 +129,7 @@ app.use(Badge);
| color | 徽标背景颜色 | _string_ | `#ee0a24` |
| dot | 是否展示为小红点 | _boolean_ | `false` |
| max | 最大值,超过最大值会显示 `{max}+`,仅当 content 为数字时有效 | _number \| string_ | - |
| offset `v3.0.5` | 设置徽标的偏移量,数组的两项分别对应水平和垂直方向的偏移量 | _[number, number]_ | - |
### Slots

View File

@ -1,4 +1,4 @@
import type { PropType } from 'vue';
import type { PropType, CSSProperties } from 'vue';
import { isDef, createNamespace } from '../utils';
import { isNumeric } from '../utils/validate/number';
@ -9,6 +9,7 @@ export default createComponent({
dot: Boolean,
max: [Number, String],
color: String,
offset: (Array as unknown) as PropType<[number, number]>,
content: [Number, String],
tag: {
type: String as PropType<keyof HTMLElementTagNameMap>,
@ -38,10 +39,25 @@ export default createComponent({
const renderBadge = () => {
if (hasContent() || props.dot) {
const style: CSSProperties = {
background: props.color,
};
if (props.offset) {
const [x, y] = props.offset;
if (slots.default) {
style.top = `${y}px`;
style.right = `${-x}px`;
} else {
style.marginTop = `${y}px`;
style.marginLeft = `${x}px`;
}
}
return (
<div
class={bem({ dot: props.dot, fixed: !!slots.default })}
style={{ background: props.color }}
style={style}
>
{renderContent()}
</div>

View File

@ -40,3 +40,32 @@ test('should render content slot correctly', () => {
expect(wrapper.html()).toMatchSnapshot();
});
test('should change dot position when using offset prop', () => {
const wrapper = mount(Badge, {
props: {
dot: true,
offset: [2, 4],
},
slots: {
default: () => 'Child',
},
});
const badge = wrapper.find('.van-badge').element;
expect(badge.style.top).toEqual('4px');
expect(badge.style.right).toEqual('-2px');
});
test('should change dot position when using offset prop without children', () => {
const wrapper = mount(Badge, {
props: {
dot: true,
offset: [2, 4],
},
});
const badge = wrapper.find('.van-badge').element;
expect(badge.style.marginTop).toEqual('4px');
expect(badge.style.marginLeft).toEqual('2px');
});