如何在 Vue 中使用窗口大小? (如何检测软键盘?)

新手上路,请多包涵

在我的带有 Vue 的移动网络应用程序中,我想在软键盘弹出时隐藏我的页脚。所以我有一个小功能来测试窗口高度与窗口宽度的比率……

 showFooter(){
    return h / w > 1.2 || h > 560;
}

…我在我的数据中声明了 window.innerHeight/window.innerWidth 。

     data: { h: window.innerHeight, w: window.innerWidth }

麻烦的是,当 window.innerHeight 改变时,我的 h 属性没有得到新的值。如何观看 window.innerHeight ?

原文由 bbsimonbb 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 390
2 个回答

要获取浏览器更改时的当前窗口高度,请使用以下脚本:

 new Vue({
  el: '#app',
  data() {
    return {
      windowHeight: window.innerHeight
    }
  },

  mounted() {
    this.$nextTick(() => {
      window.addEventListener('resize', this.onResize);
    })
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.onResize);
  },

  methods: {
    onResize() {
      this.windowHeight = window.innerHeight
    }
  }
});

如何显示信息:

 <div id="app">
 Current height: {{ windowHeight }}
</div>

原文由 samayo 发布,翻译遵循 CC BY-SA 4.0 许可协议

VUE 2.7 及以上

在 Vue 2.7+ 中,您可以创建一个返回响应宽度和断点名称的组合。

 import { computed, onMounted, onUnmounted, ref } from "vue"

export const useBreakpoints = () => {
  let windowWidth = ref(window.innerWidth)

  const onWidthChange = () => windowWidth.value = window.innerWidth
  onMounted(() => window.addEventListener('resize', onWidthChange))
  onUnmounted(() => window.removeEventListener('resize', onWidthChange))

  const type = computed(() => {
    if (windowWidth.value < 550) return 'xs'
    if (windowWidth.value >= 550 && windowWidth.value < 1200) return 'md'
    if (windowWidth.value >= 1200) return 'lg'
    return null; // This is an unreachable line, simply to keep eslint happy.
  })

  const width = computed(() => windowWidth.value)

  return { width, type }
}

您可以在组件的设置方法中使用它。

 const { width, type } = useBreakpoints()

快速提示:出于性能原因,出于性能原因,最好只在应用程序中使用一次。

  • 制作一个小插件并将值添加到 Vue 实例,就像 Vuetify 一样。

  • 或者使用提供和注入。

  • 或者将它们提交给您的全局状态管理解决方案。

原文由 kshksdrt 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题