• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

vue子组件使用window.onresize()只执行一次

武飞扬头像
小三金
帮助1

描述:

做了个简单的echarts组件,其中有个功能是当窗口变化时,刷新echarts。用了window.onresize(),且用了防抖方法,但是一个页面中会有多处用到echarts的组件,重点是当将窗口拖拽时,却只执行了一次。

  1.  
    window.onresize = () => {
  2.  
    delay(function () {
  3.  
    //防抖重画
  4.  
    _this.handleDispose()
  5.  
    _this.handleDraw()
  6.  
    }, 500)
  7.  
    }

解决方案:

使用window.addEventListener('resize',function(){})

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

区别:

  1. window.addEventListener():为每个事件指定一个回调函数去处理,简单说,以我这个组件为例,是为每个组件都指定了一个回调函数处理
  2. window.onresize():是统一用一个回调去去处理,简单说,N个子组件都用了一个同一个函数去处理,所以,只能最后一个子组件好用,因为后者覆盖了前面的方法

tips:

  1. 根据你的业务逻辑,别忘了removeEventListener(),否则它会一直监听
  2. 如果你的是后台管理系统,且有多页tabs功能(开多页功能),那么你要监听下route并做好除去监听方法,否则它也会一直监听

学新通

学新通

  1.  
    watch: {
  2.  
    options (newVal, oldVal) {
  3.  
    let _this = this
  4.  
    if (newVal) {
  5.  
    _this.init()
  6.  
    }
  7.  
    },
  8.  
    $route: {
  9.  
    handler: function (route) {
  10.  
    const _this = this
  11.  
     
  12.  
    if (route.name != "Index") {
  13.  
    //移除监听
  14.  
    window.removeEventListener('resize', _this.handleReDraw)
  15.  
    } else {
  16.  
    //监听窗口变化
  17.  
    window.addEventListener('resize', _this.handleReDraw)
  18.  
    }
  19.  
     
  20.  
    },
  21.  
    immediate: true,
  22.  
    },
  23.  
    },
学新通

学新通

  1.  
    ...
  2.  
    // 页面初始化
  3.  
    created () { },
  4.  
    // 页面DOM加载完成
  5.  
    mounted () {
  6.  
    let _this = this
  7.  
    _this.init()
  8.  
     
  9.  
    //监听窗口变化
  10.  
    window.addEventListener('resize', _this.handleReDraw)
  11.  
     
  12.  
    },
  13.  
    //离开页面时执行
  14.  
    destroyed () {
  15.  
    const _this = this
  16.  
     
  17.  
    //移除监听
  18.  
    window.removeEventListener('resize', _this.handleReDraw)
  19.  
    },
  20.  
    ...
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhibeafj
系列文章
更多 icon
同类精品
更多 icon
继续加载