Vue function that tracks the size of an HTML element.
This function is based on the ResizeObserver API.
Please note that ResizeObserver does not work on certain browsers such as IE/Edge/Safari, therefore you should add a polyfill such as:
import { ResizeObserver } from '@juggle/resize-observer'
window.ResizeObserver = window.ResizeObserver || ResizeObserver
function useSize(
elRef: Ref<null | HTMLElement>,
options?: ResizeObserverObserveOptions,
runOnMount?: boolean
): {
observedEntry: Ref<ResizeObserverEntry | null>
isTracking: Ref<boolean>
start: () => void
stop: () => void
}
elRef: Ref<null | HTMLElement>
the element to observe for size changesoptions: ResizeObserverObserveOptions
the ResizeObserver optionsrunOnMount: boolean
whether to observe the element on mount,true
by default
observedEntry: Ref<ResizeObserverEntry | null>
the observed entryisTracking: Ref<boolean>
whether this function observer is running or notstart: Function
the function used for start observingstop: Function
the function used for stop observing
<template>
<div class="box" ref="elRef">
<div class="box__msg">Resize me!</div>
<div class="box__info">{{ width }} {{ height }}</div>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import { useSize } from 'vue-use-kit'
import { ref, watch } from '@src/api'
export default Vue.extend({
name: 'UseSizeDemo',
setup() {
const elRef = ref(null)
const width = ref(0)
const height = ref(0)
const { observedEntry } = useSize(elRef)
watch(observedEntry, () => {
if (!observedEntry.value) return
width.value = observedEntry.value.contentRect.width
height.value = observedEntry.value.contentRect.height
})
return { elRef, width, height }
}
})
</script>
<style scoped>
.box {
resize: both;
overflow: auto;
}
</style>