监听页面宽高
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
- 实测中,方法一不好用, 容易出现不生效的情况,在父、子组件中同时使用了window.onresize,子组件中window.onresize无效。
- 方法二实际使用效果良好
- vue3自带useWindowSize最为简单易用