Vue2 & ElementUI实现管理后台之监听Window.resize


在用Vue2&ElementUI实现管理后台框架的时候,碰到一个问题:main块的高度没有自适应,页面留了一大块的空白。

首先想到的就是用计算属性来实现,但是在窗口变化时,计算属性并没有变化。接着想到监听Window.resize。

找了一下,发现一篇相关的文章: VueJs 监听 window.resize 方法
感谢作者提供的思路,确实可以解决问题。最后又尝试优化了一下:

<template>
  <div id="app">
      <!-- 头部导航 -->
      <header></header>
      <main v-bind:style="{ 'height': mainHeight + 'px'}">
      </main>
   </div>
 </template>
<script>
  import Lodash from 'lodash'
  export default {
    name: 'app',
    data: function () {
      return {
        mainHeight: document.body.clientHeight
      }
    },
    mounted: function () {
      const that = this
      // _.debounce 是一个通过 lodash 限制操作频率的函数。
      window.onresize = _.debounce(() => {
        console.log("onresize:" + that.mainHeight)
        that.mainHeight = document.body.clientHeight
      }, 400)
    }
  }
</script>

首先,定义 mainHeight 属性,并把 document.body.clientHeight 窗口高度的值赋给 mainHeight 属性。

mainHeight: document.body.clientHeight

然后,绑定内联样式:

v-bind:style="{ 'height': mainHeight + 'px'}"

最后,在vue挂载之后,监听窗口的resize事件。这里用到了Lodash工具库,来延迟resize的响应频率。

window.onresize = _.debounce(() => {
        console.log("onresize:" + that.mainHeight)
        that.mainHeight = document.body.clientHeight
      }, 400)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容