[Vuejs]-AddEventListener to element clientWidth vue 3

0👍

Im not expert on resizeObsever but I think component like this is working for me. Not claiming perfect but its working for my purposes.. Feel free to improve it. And idk if works in every browser or whatever if works in chrome then good with me but didnt test everything

import { onUnmounted, ref } from "vue"
export default function () {
  const elWidth = ref(0)
  const theEl = ref(null)
  const useElID = ref(null)
  function mountObserver(elID){
    useElID.value = elID
    console.log('elWidtMounted', elID)
    theEl.value = document.querySelector(elID)
    ro.observe(theEl.value);
  }
  onUnmounted(() => {
    console.log('elWidtUnMounted', useElID.value)
    ro.unobserve(theEl.value)
  })
  const ro = new ResizeObserver(entries => {
    console.log('Size changed', entries);
    for (let entry of entries) {
      console.log('Size changed e', entry);
      const width = entry.contentRect.width
      elWidth.value = width
    }
  });
  return { elWidth, mountObserver }
}

Leave a comment