diff --git a/packages/core/useElementSize/demo.vue b/packages/core/useElementSize/demo.vue index 49aa3148939..14a76688696 100644 --- a/packages/core/useElementSize/demo.vue +++ b/packages/core/useElementSize/demo.vue @@ -4,7 +4,13 @@ import { stringify } from '@vueuse/docs-utils' import { useElementSize } from '@vueuse/core' const el = ref(null) -const size = reactive(useElementSize(el)) +const size = reactive( + useElementSize( + el, + { width: 0, height: 0 }, + { box: 'border-box' }, + ), +) const text = stringify(size) diff --git a/packages/core/useElementSize/index.ts b/packages/core/useElementSize/index.ts index fc940e958db..32d313dffd5 100644 --- a/packages/core/useElementSize/index.ts +++ b/packages/core/useElementSize/index.ts @@ -22,21 +22,40 @@ export function useElementSize( initialSize: ElementSize = { width: 0, height: 0 }, options: UseResizeObserverOptions = {}, ) { + const { box = 'content-box' } = options const width = ref(initialSize.width) const height = ref(initialSize.height) useResizeObserver( target, ([entry]) => { - width.value = entry.contentRect.width - height.value = entry.contentRect.height + const boxSize = box === 'border-box' + ? entry.borderBoxSize + : box === 'content-box' + ? entry.contentBoxSize + : entry.devicePixelContentBoxSize + + if (boxSize) { + width.value = boxSize.reduce((acc, { inlineSize }) => acc + inlineSize, 0) + height.value = boxSize.reduce((acc, { blockSize }) => acc + blockSize, 0) + } + else { + // fallback + width.value = entry.contentRect.width + height.value = entry.contentRect.height + } }, options, ) - watch(() => unrefElement(target), (ele) => { - width.value = ele ? initialSize.width : 0 - height.value = ele ? initialSize.height : 0 - }) + + watch( + () => unrefElement(target), + (ele) => { + width.value = ele ? initialSize.width : 0 + height.value = ele ? initialSize.height : 0 + }, + ) + return { width, height, diff --git a/packages/core/useResizeObserver/index.ts b/packages/core/useResizeObserver/index.ts index 2acb815e2c8..c4681371011 100644 --- a/packages/core/useResizeObserver/index.ts +++ b/packages/core/useResizeObserver/index.ts @@ -24,11 +24,11 @@ export type ResizeObserverCallback = (entries: ReadonlyArray