Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

eventListener 'resize' doesnt change the value of a data() variable in Vue.js

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?

like image 561
Carlos Pisarello Avatar asked Oct 19 '25 04:10

Carlos Pisarello


2 Answers

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)
    });
  },
like image 90
sliptype Avatar answered Oct 21 '25 18:10

sliptype


@sliptype is correct, but with es6 you could do this with a lambda function

mounted() {
    window.addEventListener('resize', () => 
        this.sliderWidth = document.getElementById('slider').offsetWidth
    )
}
like image 34
bflemi3 Avatar answered Oct 21 '25 18:10

bflemi3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!