Scenario: I have a div with the ID 'slider' and i have to store the reactive value of its offsetWidth inside a variable on the data function of the component.
So i made something like this:
<template>
<div id="slider">
</div>
</template>
<script>
export default {
name: 'Slider',
mounted() {
window.addEventListener('resize', function () {
this.sliderWidth = document.getElementById('slider').offsetWidth;
});
},
data() {
return {
sliderWidth: 0,
};
},
methods: {
},
};
</script>
and then i added a method to see the current sliderWidth value
methods: {
callwidth() {
console.log(this.sliderWidth);
}
},
and added that method to the @click event on the div:
<div id="slider" @click="callWidth">
</div>
but then something strange started to happen, when i clicked on the slider after resizing the window its value was always 0.
so i added a console log on the event listener like this:
mounted() {
window.addEventListener('resize', function () {
this.sliderWidth = document.getElementById('slider').offsetWidth;
console.log(this.sliderWidth)
});
},
and when i resize the windows, it throws a new value on the console log of the eventlistener every time, but if i click on the div, the console.log of the callWidth function throws 0, why is that?
It's because your this
scope is different inside the event handler. Try:
mounted() {
let _this = this;
window.addEventListener('resize', function () {
_this.sliderWidth = document.getElementById('slider').offsetWidth;
console.log(_this.sliderWidth)
});
},
@sliptype is correct, but with es6 you could do this with a lambda function
mounted() {
window.addEventListener('resize', () =>
this.sliderWidth = document.getElementById('slider').offsetWidth
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With