zb-admin/src/hooks/useResizeHandler.ts

71 lines
1.9 KiB
TypeScript
Raw Normal View History

import {useSettingStore} from "@/store/modules/setting"
2022-04-06 07:48:24 +00:00
import {computed, onMounted, onUnmounted, watch} from "vue";
import {useRoute} from "vue-router";
const { body } = document
const WIDTH = 800 // refer to Bootstrap's responsive design
const MAX_WIDTH = 1200
2022-04-06 07:48:24 +00:00
export const useResizeHandler = ()=>{
const SettingStore = useSettingStore()
2022-04-06 07:48:24 +00:00
const route = useRoute()
const device = computed(()=>{
return SettingStore.device
2022-04-06 07:48:24 +00:00
})
function $_isMobile(){
const rect = body.getBoundingClientRect()
return rect.width - 1 < WIDTH
}
function collapse(){
const rect = body.getBoundingClientRect()
if(rect.width - 1 > MAX_WIDTH){
return true
}else {
return false
}
}
2022-04-06 07:48:24 +00:00
function $_resizeHandler(){
if (!document.hidden) { // bool型表示页面是否处于隐藏状态。页面隐藏包括页面在后台标签页或者浏览器最小化
const isMobile = $_isMobile()
const isCollapse = collapse()
SettingStore.toggleDevice(isMobile ? 'mobile' : 'desktop')
2022-04-06 07:48:24 +00:00
2022-04-06 07:48:24 +00:00
if (isMobile) {
SettingStore.closeSideBar({ withoutAnimation: true })
2022-04-06 07:48:24 +00:00
}
if(!isMobile){
SettingStore.setCollapse(isCollapse)
}
2022-04-06 07:48:24 +00:00
}
}
onMounted(()=>{
const isMobile = $_isMobile()
if (isMobile) {
SettingStore.toggleDevice('mobile')
SettingStore.closeSideBar({ withoutAnimation: true })
2022-04-06 07:48:24 +00:00
}
window.addEventListener('resize', $_resizeHandler)
watch(route,()=>{
if (device.value === 'mobile' && SettingStore.isCollapse) {
SettingStore.closeSideBar({ withoutAnimation: false })
2022-04-06 07:48:24 +00:00
}
})
})
onUnmounted(()=>{
window.removeEventListener('resize', $_resizeHandler)
})
return {device}
}