Hey there, I'm currently working on a project where I need to track the clientWidth of a component when it gets resized. I'm trying to achieve this by using:
const myEl = document.querySelector('#myID')
and monitoring changes in myEl.clientWidth. I haven't been able to find a function that specifically watches for element size changes, as most solutions focus on screen resizing. Here's an example of a function that works for screen resize:
import { onMounted, onUnmounted, ref } from "vue"
export default function () {
let width = ref(window.innerWidth)
const onWidthChange = () => width.value = window.innerWidth
onMounted(() => window.addEventListener('resize', onWidthChange))
onUnmounted(() => window.removeEventListener('resize', onWidthChange))
return { width }
}
But what I'm attempting is slightly different:
import { onMounted, onUnmounted, ref } from "vue"
export default function (el) {
let elWidth = ref(null)
function onWidthChange(){
console.log('HERE')
elWidth.value = el.clientWidth
}
onMounted(() => el.addEventListener('resize', onWidthChange))
onUnmounted(() => el.removeEventListener('resize', onWidthChange))
return { elWidth }
}
I want to pass 'myEl' into the component and utilize it like so:
const myEl = ref(null)
onMounted(() => {
myEl.value = document.querySelector("#myEl")
const { elWidth } = useElementWidth(myEl.value)
watch(() => elWidth.value,
(wid) => {
if(wid){
console.log('widEL', wid )
}
},
})
})
While being composable isn't mandatory, my main goal is to successfully monitor the clientWidth of the element.