SoFunction
Updated on 2025-04-04

Solve the pitfalls encountered by adding and removing resize events to window by vue

In the vue project, you need to listen to the window changes to calculate the height of the picture at any time, so a listening event was added; it was indeed listened, but when you leave the current page and enter other pages to change the window size, it is found that the window is still in the listening state, that is, the removal of the listening event has not taken effect.

  //The previous writing method, this way of writing remove the listening event is invalid  mounted(){
    ('resize',()=>{
      'The processing needs to be done when changing the window'
    });
  },
  beforeDestroy() {
    ("resize");
  }

Later, after searching for relevant information, I found that the following writing method can be used to remove the monitoring

  methods: {
    listenResize(){
      'Operation when window size changes'
    }
  },
  mounted(){
    ('resize',); 
  },
  beforeDestroy() {
    ("resize",);
  }

Supplementary knowledge:vue listening screen changes & destroy listening events

Remember a small pit.

Since using echarts requires an adaptive screen, we use the listening event in vue and consider the performance issues, so we use the debounce of the lodash library to wrap it. The code is as follows:

mounted() {
  ('resize', debounce(,200), true)
},
beforeDestroy() {
  ('resize', , true)
},
methods: {
  resize() {
   ()
  }
}

However, when switching to other pages, the resize event will still be triggered when the screen changes. Because I have written similar functions before, there is no problem with the code, but it will be triggered. I also felt strange in my heart. After studying it, I found that the addEventListener method does not add debounce. As follows:

mounted() {
  ('resize', , true)
},
beforeDestroy() {
  ('resize', , true)
},
methods: {
  resize: debounce(function() {
   ()
  }, 300),
 }

debounce needs to be added in methods. And the internal function body cannot use arrow functions, otherwise this undefined problem will be reported

The above article solves the pitfalls encountered by adding and removing resize to window by vue is all the content I share with you. I hope you can give you a reference and I hope you can support me more.