From 78847b83759ecbee5af235da029d85ebb479f096 Mon Sep 17 00:00:00 2001 From: Gavin <19986739+wjw-gavin@users.noreply.github.com> Date: Sat, 24 Dec 2022 12:54:40 +0800 Subject: [PATCH] fix(Badge): fix badge offset of different position (#11400) * fix(Badge): fix badge offset of different position * perf: improve code --- packages/vant/src/badge/Badge.tsx | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/packages/vant/src/badge/Badge.tsx b/packages/vant/src/badge/Badge.tsx index ef6aea92b..341c1ba5c 100644 --- a/packages/vant/src/badge/Badge.tsx +++ b/packages/vant/src/badge/Badge.tsx @@ -71,6 +71,9 @@ export default defineComponent({ } }; + const getOffsetWithMinusString = (val: string) => + val.startsWith('-') ? val.replace('-', '') : `-${val}`; + const style = computed(() => { const style: CSSProperties = { background: props.color, @@ -78,13 +81,23 @@ export default defineComponent({ if (props.offset) { const [x, y] = props.offset; + const { position } = props; + const offsetY = position.indexOf('top') > -1 ? 'top' : 'bottom'; + const offsetX = position.indexOf('left') > -1 ? 'left' : 'right'; + if (slots.default) { - style.top = addUnit(y); + if (typeof y === 'number') { + style[offsetY] = addUnit(offsetY === 'top' ? y : -y); + } else { + style[offsetY] = + offsetY === 'top' ? addUnit(y) : getOffsetWithMinusString(y); + } if (typeof x === 'number') { - style.right = addUnit(-x); + style[offsetX] = addUnit(offsetX === 'left' ? x : -x); } else { - style.right = x.startsWith('-') ? x.replace('-', '') : `-${x}`; + style[offsetX] = + offsetX === 'left' ? addUnit(x) : getOffsetWithMinusString(x); } } else { style.marginTop = addUnit(y);