heritage-hub/src/utils/self-adaption.js

40 lines
1.3 KiB
JavaScript
Raw Normal View History

2024-02-01 10:38:40 +00:00
import { ref, onMounted, onBeforeUnmount } from 'vue';
export function useAdaptation(handleChange) {
const mediaQuery = '(max-width: 768px)';
const currentDevice = ref(window.matchMedia(mediaQuery).matches ? 'mobile' : 'pc');
const changeHandler = (newValue) => {
if (typeof handleChange === 'function') {
handleChange(newValue);
}
};
const mediaQueryChangeHandler = event => {
const newDevice = event.matches ? 'mobile' : 'pc';
changeHandler(newDevice); // 使用钩子函数
currentDevice.value = newDevice; // 更新currentDevice值
};
let mediaQueryList;
onMounted(() => {
mediaQueryList = window.matchMedia(mediaQuery);
mediaQueryList.addEventListener('change', mediaQueryChangeHandler);
mediaQueryChangeHandler(mediaQueryList);
});
onBeforeUnmount(() => {
mediaQueryList.removeEventListener('change', mediaQueryChangeHandler);
});
const currentDeviceProxy = new Proxy(currentDevice, {
set(target, prop, value) {
if (prop === 'value' && target[prop] !== value) {
changeHandler(value);
}
return Reflect.set(target, prop, value);
}
});
return { currentDevice: currentDeviceProxy };
}