web端 vue获取屏幕的宽度和高度 和 实时监听窗口宽度变化

454 阅读1分钟

获取屏幕的宽度和高度

  • 网页可见区域宽:document.body.clientWidth
  • 网页可见区域高:document.body.clientHeight
  • 网页可见区域宽:document.body.offsetWidth (包括边线的宽)
  • 网页可见区域高:document.body.offsetHeight (包括边线的宽)

设备的宽度和高度

  • 设备宽度:window.innerWidth
  • 设备高度:window.innerHeight

实时监听窗口宽度变化

在页面mounted时,挂载window.onresize方法:

mounted () {
    window.onresize = () => {
        return (() => {
          console.log(document.documentElement.clientWidth);
        })()
    }
},

记住要在页面销毁时关闭,不然如果路由缓存会出问题

beforeDestroy () {
  window.onresize = null;
},