美文网首页VueVue.js 资料vue之路
Vue2 & ElementUI实现管理后台之监听Win

Vue2 & ElementUI实现管理后台之监听Win

作者: 0非空0 | 来源:发表于2017-01-23 17:43 被阅读2733次

在用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)

相关文章

网友评论

  • 7447e3c43d9f:如果说存在多个*.vue需要监听的时候,就来问题来,onresize只能注册一个
    212ae36e1744:如果想多处监听onresize,怎么抽象出全局 ,然后其他组件直接使用啊

本文标题:Vue2 & ElementUI实现管理后台之监听Win

本文链接:https://www.haomeiwen.com/subject/beajjttx.html