52 lines
1.2 KiB
TypeScript
Raw Normal View History

2022-08-22 16:57:55 +08:00
import { watch, onBeforeMount, onMounted, onBeforeUnmount } from "vue"
import { useRoute } from "vue-router"
import { useAppStore, DeviceEnum } from "@/store/modules/app"
2022-08-22 16:57:55 +08:00
/** 参考 Bootstrap 的响应式设计 WIDTH = 992 */
const WIDTH = 992
/** 根据大小变化重新布局 */
export default () => {
const route = useRoute()
const appStore = useAppStore()
const _isMobile = () => {
const rect = document.body.getBoundingClientRect()
return rect.width - 1 < WIDTH
}
const _resizeHandler = () => {
if (!document.hidden) {
const isMobile = _isMobile()
appStore.toggleDevice(isMobile ? DeviceEnum.Mobile : DeviceEnum.Desktop)
2022-08-22 16:57:55 +08:00
if (isMobile) {
appStore.closeSidebar(true)
}
}
}
watch(
() => route.name,
() => {
if (appStore.device === DeviceEnum.Mobile && appStore.sidebar.opened) {
2022-08-22 16:57:55 +08:00
appStore.closeSidebar(false)
}
}
)
onBeforeMount(() => {
window.addEventListener("resize", _resizeHandler)
})
onMounted(() => {
if (_isMobile()) {
appStore.toggleDevice(DeviceEnum.Mobile)
2022-08-22 16:57:55 +08:00
appStore.closeSidebar(true)
}
})
onBeforeUnmount(() => {
window.removeEventListener("resize", _resizeHandler)
})
}