Asked By: Anonymous
I’m trying to dynamically set the width of my innermost element equal to the width of the outermost element using Vue:
<div id="banner-container" class="row">
<div class="col-xs-12">
<div class="card mb-2">
<div class="banner banner-tag card-body" :style="getBannerStyle"></div>
</div>
</div>
</div>
I have the following code in Javascript and computed property in Vue:
var container = document.getElementById('banner-container').offsetWidth;
...
computed: {
getBannerStyle () {
return 'width: ' + container + 'px;';
}
}
Solution
Answered By: user320487
getBannerStyle
is not going to be reactive because you do not access any other reactive properties within it. You need to assign a data property the offsetWidth value and reference that within getBannerStyle
. Something like this should work:
mounted () {
this.offsetWidth = document.getElementById('banner-container').offsetWidth
},
data () {
return {
offsetWidth: 0,
}
},
computed: {
getBannerStyle () {
return `width: ${this.offsetWidth}px;`
}
}