Vuejs 2 + event listener (window resize)

Hi guys,
I’m trying to get window width and height size. Also, I want to catch the size when the window resizes.

I have seen this comment here. However, I’ve tried to do it with Vuejs 2 and didn’t work.

Follow my jsfiddle:

What I’m missing?

1 Like


Hi i made it with data


That is so weird!
I just change this bit
this.$nextTick(function() {
window.addEventListener(‘resize’, this.getWindowWidth());
window.addEventListener(‘resize’, this.getWindowHeight());

to without () at the end of the function.
this.$nextTick(function() {
window.addEventListener(‘resize’, this.getWindowWidth);
window.addEventListener(‘resize’, this.getWindowHeight);

And it works!

Tks anyway

Woops I read that wrong. By putting the parenthesis in the callback for eventListener you’re executing the method immediately. You need to pass a reference to it, which you found out by not supplying the ()

Yep, I could notice that I should you something like this

window.addEventListener(‘resize’, function() {

That works!

Tks anyway


A little off-topic: why are you guys passing a function to the Data property? Shouldn’t you do this only on components?

It doesn’t hurt in the main instance, it just isn’t necessary, while im components it is.

1 Like

Hi @tiagomatosweb!
I’m a ur subscriber … U have this exemple in a JSfiddle… I’m trying resize a component by sizes another component… U can help me?

@AdsonCicilioti, sorry for delaying. Yes I can help you. Whats up?
Can you share your code and explain in more detail?

How do you remove the added event listener ?

@Uthpala_419 check beforeDestroy

1 Like
destroyed() {
   window.removeEventListener("resize", this.your_function);

Your example was awesome, one thing I’m wondering is, practically, what the advantage of having mounted code be nested inside the this.$nextTick(function() {...}

removing it in the sample code, seemed to operate identically, but I’m wondering if there’s a performance reason maybe why nextTick should be used?