监听页面宽高

window.onresize

mounted(){
  window.onresize = function() {
      this.windowHeight = document.documentElement.clientHeight // 高
      this.windowWidth = document.documentElement.clientWidth // 宽
  }
}

window.addEventListener

mounted() {
    window.addEventListener('resize', () => {
    this.windowHeight = document.documentElement.clientHeight // 高
    this.windowWidth = document.documentElement.clientWidth // 宽
  })
}

vue3

import { useWindowSize } from '@vueuse/core'
import { watchEffect } from 'vue'
const { width, height } = useWindowSize()
watchEffect(() => {
  changeMobile(width.value - 1 < 992)
  changeCollapse(width.value - 1 < 1010)
})

tips

  1. 实测中,方法一不好用, 容易出现不生效的情况,在父、子组件中同时使用了window.onresize,子组件中window.onresize无效。
  2. 方法二实际使用效果良好
  3. vue3自带useWindowSize最为简单易用
Last Updated:
Contributors: haizhiguang