Phoenix 8 months ago
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 };
}

@ -2,15 +2,16 @@
import { ref, onMounted, onBeforeUnmount } from "vue";
import PcIndex from '@/views/navigation/pc-index.vue';
import ModelIndex from '@/views/navigation/model-index.vue';
import {useAdaptation} from '@/utils/self-adaption.js'
const {currentDevice}= useAdaptation((currentDevice)=>{
console.log(currentDevice,'currentDevice')
})
const mediaQuery = '(max-width: 768px)';
const currentComponent = ref(window.matchMedia(mediaQuery).matches ? ModelIndex : PcIndex);
function handleMediaQuery(event) {
currentComponent.value = event.matches ? ModelIndex : PcIndex;
}
let mediaQueryList;
onMounted(() => {
mediaQueryList = window.matchMedia(mediaQuery);
mediaQueryList.addEventListener('change', handleMediaQuery);

Loading…
Cancel
Save