window.onresize事件在vue项目中的应用

本文介绍了在Vue项目中应用window.onresize事件的注意事项,包括事件的触发时机,this指向问题,以及如何避免全局事件的影响。强调了在特定生命周期钩子中绑定和解除事件的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

window.onresize事件在vue项目中的应用

//vue页面
<template> <div id='echart'> 报表 </div> </template> <script> export default { data() { return { }; }, methods: { pageResize(){ this.$nextTick(()=>{ var echart = document.getElementById('echart'); echart.style.height = document.documentElement.offsetHeight-220 + 'px' }) } },
  //挂载window.onresize事件 mounted(){ let _this
= this;//赋值vue的this window.onresize = ()=>{
    //调用methods中的事件 _this.pageResize(); } },
  //注销window.onresize事件 destroyed(){ window.onresize
= null; } } </script> <style lang="scss"> #echart{ background-color: #fff; border-radius: 4px; padding: 20px; min-height: 400px; } </style>

注意事项:

1、window.onresize事件一般放在created或者mounted生命周期中,这样界面改变是能触发。

2、window.onresize中的this指向的是window,不是指向vue,如果需要调用methods中的函数,需要在window.onresize事件的前面把指向vue的this赋值给其他字符,比如"_this"。

3、由于window.onresize是全局事件,在其他页面改变界面时也会执行,这样可能会出现问题,需要在出这个界面时注销window.onresize事件。

4、window.onresize说明一个问题:beforeCreate、created、beforeMount、mounted、beforeUpdate、updated中的会触发浏览器事件需要在destroyed、beforeDestory中销毁掉。

 

posted @ 2019-04-23 10:00 或许这就是生活 阅读( ...) 评论( ...) 编辑 收藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值