Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ren8179 opened this issue Jan 23, 2017 · 0 comments
Open

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

ren8179 opened this issue Jan 23, 2017 · 0 comments

Comments

@ren8179
Copy link
Owner

ren8179 commented Jan 23, 2017


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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant