Created
September 28, 2023 10:49
-
-
Save DesignHhuang/d27a919f5bff60c7f097238a03b2d5b6 to your computer and use it in GitHub Desktop.
useViewport:使用视口
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ref, onMounted, onUnmounted } from 'vue'; | |
export const MOBILE = 'MOBILE' | |
export const TABLET = 'TABLET' | |
export const DESKTOP = 'DESKTOP' | |
export const useViewport = (config = {}) => { | |
const { mobile = null, tablet = null } = config; | |
let mobileWidth = mobile ? mobile : 768; | |
let tabletWidth = tablet ? tablet : 922; | |
let device = ref(getDevice(window.innerWidth)); | |
function getDevice(width) { | |
if (width < mobileWidth) { | |
return MOBILE; | |
} else if (width < tabletWidth) { | |
return TABLET; | |
} | |
return DESKTOP; | |
} | |
const handleResize = () => { | |
device.value = getDevice(window.innerWidth); | |
} | |
onMounted(() => { | |
window.addEventListener('resize', handleResize); | |
}); | |
onUnmounted(() => { | |
window.removeEventListener('resize', handleResize); | |
}); | |
return { | |
device | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment