I have a navigation bar component with a variable width in the following format:
<template>
<div class="container">
<div v-if="!!$scopedSlots.menu">
<slot name="menu" />
</div>
...
</div>
</template>
I am creating a new component that can be slotted in to that "menu" slot which should function as a button that opens a dropdown the width of the entire nav bar.
Is there a good way to reactively monitor the width of that container
from within the child component? I am able to get its initial width in mounted()
like so:
this.parentWidth = (this.$parent.$parent.$el as HTMLElement).offsetWidth;
This only gets me the initial width of that element though. If its container grows the child component will not grow reactively. I've tried changing this assignment to a computed value but I can't access the parent element when the page is rendered and the styles
computed comes back undefined or in the case below with width: 'auto'
no matter what:
computed: {
styles() {
const parent = this.$parent.$parent.$el as HTMLElement;
if(!!parent) {
return {width: `${parent.offsetWidth}px`};
} else {
return {width: 'auto'};
}
}
}