Using window.onresize() in a vue subcomponent only executes it once

describe:

I made a simple echarts component, which has a function to refresh echarts when the window changes. Window.onresize() is used, and the anti-shake method is used, but the echarts component is used in multiple places on a page. The key point is that when the window is dragged, it is only executed once.

window.onresize = () => {
                delay(function () {
                    //防抖重画                    
                    _this.handleDispose()
                    _this.handleDraw()
                }, 500)
            }

solution:

use window.addEventListener('resize',function(){})

window.addEventListener('resize', _this.handleReDraw)

the difference:

  1. window.addEventListener(): Specify a callback function for each event to process. To put it simply, taking my component as an example, a callback function is specified for each component to process.
  2. window.onresize(): is processed by a unified callback. To put it simply, N sub-components are processed by the same function. Therefore, only the last sub-component can be used because the latter covers the previous method .

tips:

  1. According to your business logic, don't forget to removeEventListener(), otherwise it will keep listening
  2. If yours is a background management system with multi-page tabs function (multi-page function enabled), then you need to monitor the route and remove the monitoring method, otherwise it will keep monitoring.

 watch: {
        options (newVal, oldVal) {
            let _this = this
            if (newVal) {
                _this.init()
            }
        },
        $route: {
            handler: function (route) {
                const _this = this

                if (route.name != "Index") {
                    //移除监听
                    window.removeEventListener('resize', _this.handleReDraw)
                } else {
                    //监听窗口变化
                    window.addEventListener('resize', _this.handleReDraw)
                }

            },
            immediate: true,
        },
    },

... 
// 页面初始化
    created () { },
    // 页面DOM加载完成
    mounted () {
        let _this = this
        _this.init()

        //监听窗口变化
        window.addEventListener('resize', _this.handleReDraw)

    },
    //离开页面时执行
    destroyed () {
        const _this = this

        //移除监听
        window.removeEventListener('resize', _this.handleReDraw)
    },
...

Guess you like

Origin blog.csdn.net/tdjqqq/article/details/124985203