Skip to content

Instantly share code, notes, and snippets.

@DesignHhuang
Created September 28, 2023 10:49
Show Gist options
  • Save DesignHhuang/d27a919f5bff60c7f097238a03b2d5b6 to your computer and use it in GitHub Desktop.
Save DesignHhuang/d27a919f5bff60c7f097238a03b2d5b6 to your computer and use it in GitHub Desktop.
useViewport:使用视口
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