Vue window.onresize监听窗口变化

示例:在webapp页面的底部,有时候我们会使用 position: absolute;bottom: 0; 实现一些需求,如tabbar,固定到底部的一些操作按钮。
问题:当页面有输入框的时候,底部的定位元素会被输入法顶到上面?
解决办法:
使用window.onresize监听窗口变化,动态修改有定位的元素css,当窗口发生变化时,让定位元素隐藏。

用法:

  1. 在store.js里定义:
    screenHeight——用于存放全局的视口高度
    changeScreenHeight ——用于动态改变视口的高度
import Vuex from 'vuex'
Vue.use(Vuex)

const store = new Vuex.Store({
  strict: true,
  state: {
    screenHeight: document.documentElement.clientHeight,
  },
  mutations: {
    changeScreenHeight (state, val) {
      state.screenHeight = val
    }
  }
})
export default store
  1. 在App.vue里挂载window.onresize,也可以使用(例:watch里)
<template>
  <div class="app">

    <div class="app-body">
      <router-view></router-view>
    </div>

    <router-view name="tabbar" :style="{ display: tabbarDisplay}"></router-view>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
  name: 'App',

  data () {
    return {
      tabbarDisplay: 'block'
    }
  },

  watch: {
    /**
    * 侦听页面可视高度的变化,将底部tabbar display:block
    */
    '$store.state.screenHeight' () {
      // 使用视口高度变量
      if (this.$router.currentRoute.name === 'insured' || this.$router.currentRoute.name === 'order') {
        this.tabbarDisplay = this.tabbarDisplay === 'block' ? 'none' : 'block'
      }
    }
  },

  methods: {
    ...mapMutations(['changeScreenHeight'])
  },

  mounted () {
    window.onresize = () => {
      this.changeScreenHeight(document.documentElement.clientHeight)
    }
  }
}
</script>
  1. 在其它子页面监听视口变化,动态操作
    直接引入就可以使用,因为window.onresize是全局注册的。
<template>
  <div class="regist">
    <div class="regist-header"></div>

    <div class="regist-body">

    <div class="regist-foot" ref="foot" style="display:block;">
        一些定位的操作按钮
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  watch: {
    screenHeight (newVal, oldVal) {
      if (Math.abs(oldVal - newVal) > 60) {
        this.$refs.foot.style.display = this.$refs.foot.style.cssText === 'display: block;' ? 'none' : 'block'
      }
    }
  },

  computed: {
    ...mapState(['screenHeight'])
  }
}
</script>

注意:

  1. 在项目中 window.onresize只能挂载一次,在多个页面中同时挂载 window.onresize时,只有其中一个 window.onresize会起作用。
  2. mutations是唯一更改store的地方,更改store里的screenHeight,必须在mutations里定义函数,在需要更改store的地方调用执行。
  3. 引入store以后,直接就可以使用,App.vue页面挂载的onresize监听是全局的。

参考:
https://blog.csdn.net/xuaner8786/article/details/81565219

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • vue去哪网跟学笔记 记录学习点滴 1. 初始化项目 1.1 手机显示配适 minimum-scale=1.0,m...
    noobakong阅读 2,290评论 0 16
  • 一:什么是闭包?闭包的用处? (1)闭包就是能够读取其他函数内部变量的函数。在本质上,闭包就 是将函数内部和函数外...
    xuguibin阅读 9,733评论 1 52
  • Vuex Vuex是vue官方的一款状态管理工具,什么是状态呢?我们在前端开发中有一个概念:数据驱动,页面中任意的...
    一条IT阅读 300评论 0 2
  • Vuex Vuex是vue官方的一款状态管理工具,什么是状态呢?我们在前端开发中有一个概念:数据驱动,页面中任意的...
    一条IT阅读 1,258评论 0 2
  • 渲染函数和jsx 在vue中我们可以不用template来指定组件的模板,而是用render函数来创建虚拟dom结...
    6e5e50574d74阅读 728评论 0 0