I’m new to vue.js and I’ve encountered a problem that I can’t fix.
In my SelectField.vue component I have written the following method:
getModalBodyElement() {
return document.querySelector('.modal-body') as HTMLElement;
},
I want to use this to customise my modal body when a multiselect field opens and the body becomes scrollable:
onDropdownOpen() {
nextTick(() => {
const modalBodyElement = this.getModalBodyElement();
// No idea why $el is not defined Multiselect extends Vue
const dropdownElement = (this.$refs.multiselect as Multiselect).$el as HTMLElement;
if (!modalBodyElement || !dropdownElement) return;
const modalRect = modalBodyElement.getBoundingClientRect();
const dropdownRect = dropdownElement.getBoundingClientRect();
const extraHeight = dropdownRect.bottom + dropdownRect.height * Math.min(this.options.length, 5);
console.log("element", modalBodyElement)
if (extraHeight > modalRect.bottom) {
this.originalModalHeight = modalBodyElement.offsetHeight;
const newHeight = this.originalModalHeight + (extraHeight - modalRect.bottom);
modalBodyElement.style.height = `${newHeight}px`;
this.heightAdjusted = true;
}
});
},
When I display the element in the console.log, it is also displayed. However, I cannot manipulate this element. In other words, this does not work: modalBodyElement.style.height
My work around was that I use a store which stores the ref from the body
<template>
<section class="modal-body" ref="modalBodyRef">
<slot name="body">My body is empty :(</slot>
</section>
</template>
export default defineComponent({
name: 'ModalBody',
setup() {
const modalBodyRef = ref<HTMLElement | null>(null);
const modalStore = useModalStore();
onMounted(() => {
if (modalBodyRef.value) {
modalStore.setModalBodyRef(modalBodyRef.value);
}
});
return {
modalBodyRef,
};
},
});
I now use this store instead of the querySelector. With some modals it works very well and with others it doesn’t work. Here the element is displayed in the console again but I cannot manipulate it. I don’t know what the problem is and hope you have an idea and can help me.
I have tried to solve my problem with the ref attribute by saving it in the store. Actually, every modal should now be able to use this ref to correctly adjust the height of the body. However, it works for some modals and not for others.
1