I have built a VueJS component and am using it multiple times on the same page. The components work independently of each other perfectly, however there's a method in the component to get it's offsetWidth and apply this (with a prefix) to the component as a class (eg width-800).
When there is only one of the component on a page, it works fine.
When there is more than one, only the last occurrence applies the class. It does calculate the class correctly with the correct width, but just doesn't apply it to the others on the page.
<template>
<div id="app-medialib" v-bind:class="[this.breakpoint]">
<p>{{ this.breakpoint }}</p>
this.breakpoint
is a data property which holds the class name.
mounted: function(){
var self = this;
this.calculateBreakpoint();
window.onresize = function(event) {
self.calculateBreakpoint();
};
}
and the breakpoint method:
calculateBreakpoint: function(){
var mediaLibraryWidth = null;
var elems = document.getElementsByClassName('header medialib');
for( var i=0; i<elems.length; i++ ){
if( elems[i].offsetParent !== null ){
console.log('elems[i]', elems[i]);
mediaLibraryWidth = elems[i].offsetWidth;
break;
}
}
console.log('calculateBreakpoint', mediaLibraryWidth);
if( mediaLibraryWidth > 956 ) {
this.breakpoint = 'md';
} else if( mediaLibraryWidth < 957 && mediaLibraryWidth > 700 ){
this.breakpoint = 'sm';
} else {
this.breakpoint = 'xs';
}
console.log('calculateBreakpoint', this.breakpoint);
},
Any help is much appreciated on this. Been scratching my head for a while now.
Thanks.