To monitordiv
The width changes can be usedResizeObserver
Interface.ResizeObserver
Allows you to observe the size changes of one or more elements and execute a callback function when it changes. This method is more useful thanMutationObserver
Focus more on size changes and are not affected by changes in element attributes.
Use ResizeObserver
First, create aResizeObserver
Instance, and pass in a callback function that will be called when the element size changes. In the callback function, you can access the new dimensions of each observed element.
const resizeObserver = new ResizeObserver(entries => { (entry => { const { width, height } = ; (`Element resized: Width=${width}, Height=${height}`); }); }); // Suppose the element you want to observe is a div with a specific IDconst observedElement = ('#yourDivId'); // Start observing the element(observedElement); // When you need to stop observing, you can call the disconnect method// ();
Use in vue3
const container = ref(null); let observer; let resizeTimer; onMounted(() => { createObserver(); }); onUnmounted(() => { if (observer) { (); } }); function createObserver() { observer = new ResizeObserver((entries) => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { for (const entry of entries) { const { width, height } = ; (width); } }, 200); }); (); }
<div ref="container"></div>
Things to note
-
ResizeObserver
It is an API supported by modern browsers, not all browsers support it. Make sure your target browser supports this API, or use polyfill to provide cross-browser compatibility. -
ResizeObserver
Only changes in the dimensions of elements can be observed, and no changes in the contents or internal layout of elements can be detected. - If you need to trigger events when the content or layout of an element changes, you may need to use other techniques in combination, such as
MutationObserver
。
This is the article about Vue3 using ResizeObserver to monitor the size and width changes of elements. For more information about Vue3 ResizeObserver to monitor width changes, please search for my previous articles or continue to browse the related articles below. I hope everyone will support me in the future!