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中銷毀掉。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM