01 window.onresize

onresize属性可以用来获取或设置当前窗口的resize事件的事件处理函数

  1. window.onresize = funcRef;
  1. //vue页面
  2. <template>
  3. <div id='echart'>
  4. vue window.onresize
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. data() {
  10. return {
  11. };
  12. },
  13. methods: {
  14. pageResize(){
  15. this.$nextTick(()=>{
  16. var echart = document.getElementById('echart');
  17. echart.style.height = document.documentElement.offsetHeight-220 + 'px'
  18. })
  19. }
  20. },
  21.   //挂载window.onresize事件
  22. mounted(){
  23. let _this = this; //赋值vue的this
  24. window.onresize = ()=>{
  25.     //调用methods中的事件
  26. _this.pageResize();
  27. }
  28. },
  29.   //注销window.onresize事件
  30. destroyed(){
  31. window.onresize = null;
  32. }
  33. }
  34. </script>
  35. <style lang="scss">
  36. #echart{
  37. background-color: #fff;
  38. border-radius: 4px;
  39. padding: 20px;
  40. min-height: 400px;
  41. }
  42. </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中销毁掉。

如果一个组件中的多个子组件中都使用了window.onrsize那么会出现只有一个起作用的情况,一般在在其他的组件中使用window.addlistenter(‘resize’,()=>{}) 这种形式去去修改;