Skip to main content

Some notes on monitoring browser window size

init-qyfront-end developmentjsvueAbout 2 min

Process

In order to use echarts charts in a vue project, the canvas-based echarts cannot change with the window size. In this case, it is necessary to listen for window size changes and dynamically execute the echarts resize method.

Add event handlers to the Window object

mounted() { window.addEventListener('resize', this.resizeHandler) }, destroyed()
{ window.removeEventListener('resize', this.resizeHandler) }, methods:{
resizeHandler(){ // do something } }

Mount the method in the window's onresize event

watch: { screenWidth(val) { //
为了避免频繁触发resize函数导致页面卡顿,使用定时器 if (!this.timer) { //
一旦监听到的screenWidth值改变,就将其重新赋给data里的screenWidth
this.screenWidth = val this.timer = true const that = this setTimeout(function()
{ // 打印screenWidth变化的值 console.log(that.screenWidth) that.timer = false //
do something }, 400) } } }, mounted () { // 监听页面大小变化 const that = this
window.onresize = () => { return (() => { window.screenWidth =
document.body.clientWidth that.screenWidth = window.screenWidth })() } }

This method is a bit cumbersome, and it also requires maintaining two additional variables in the data.

Use resize-observer-polyfill to listen for changes in DOM size

This method, compared to the previous two, can only listen for changes in window size, but it can listen for changes in element size. It can respond to some variable elements on the page. The method is derived from the source code of element-ui. Thanks to this person for the discovery: Using the resize event method encapsulated by element-uiopen in new window

The code used is from this person:

// 先引入
// 如果项目使用了element-ui,可以直接引用,或者copy一份放在自己的代码里
import {
  addResizeListener,
  removeResizeListener,
} from "element-ui/src/utils/resize-event";

export default {
  mounted() {
    // 可以在mounted这个钩子里初始化事件
    addResizeListener(this.$el, this.resizeListener);
  },
  methods: {
    resizeListener() {
      // do something
    },
  },
  // 生命周期结束时销毁事件
  destroyed() {
    if (this.resizeListener)
      removeResizeListener(this.$el, this.resizeListener);
  },
};

Use useresizeobserver from vueuse (2022-12-15)

Times have changed, and using vueuse has become very convenient. When you need to call some native browser methods, vueuse is often a good choice.
https://vueuse.org/core/useresizeobserver/#useresizeobserveropen in new window

Summary

Throughout the process, I have learned a lot by following the source code, but I haven't studied it systematically, just got a general understanding. Here is a summary:

  1. Polyfills or Ponyfills?open in new window
  2. echarts official websiteopen in new window (On January 28, 2021, echarts will release a new version. I took a look and found that besides canvas, it also uses SVG for rendering.)
  3. resize-observer-polyfillopen in new window

This post is translated using ChatGPT, please feedbackopen in new window if any omissions.