master
parent
b6778fe1d9
commit
8750c9bbfb
@ -0,0 +1,40 @@
|
||||
// useAdaptation.js
|
||||
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 };
|
||||
}
|
Loading…
Reference in New Issue