kidArtExpo/src/utils/self-adaption.js
2024-08-06 19:32:06 +08:00

47 lines
1.5 KiB
JavaScript

import { ref, onMounted, onBeforeUnmount } from 'vue'
export function useAdaptation(sizes, handleChange) {
const mediaQueryLists = sizes.map(size => window.matchMedia(`(max-width: ${size.maxWidth})`));
const currentDevice = ref(getCurrentDevice())
function getCurrentDevice() {
for (let i = 0; i < mediaQueryLists.length; i++) {
if (mediaQueryLists[i].matches) {
return sizes[i].maxWidth;
}
}
return sizes[sizes.length - 1].maxWidth
}
const changeHandler = (newValue) => {
if (typeof handleChange === 'function') {
handleChange(newValue);
}
};
const mediaQueryChangeHandler = () => {
const newDevice = getCurrentDevice();
if (currentDevice.value !== newDevice) {
currentDevice.value = newDevice;
changeHandler(newDevice);
}
};
let cleanupHandlers = [];
onMounted(() => {
mediaQueryLists.forEach(query => {
query.addEventListener('change', mediaQueryChangeHandler);
cleanupHandlers.push(() => query.removeEventListener('change', mediaQueryChangeHandler));
});
// Ensure the initial value is correct and trigger the changeHandler with the initial value
const initialDevice = getCurrentDevice();
currentDevice.value = initialDevice;
changeHandler(initialDevice);
});
onBeforeUnmount(() => {
cleanupHandlers.forEach(cleanup => cleanup());
});
return { maxWidth: currentDevice };
}