diff --git a/src/utils/self-adaption.js b/src/utils/self-adaption.js new file mode 100644 index 0000000..3d76f61 --- /dev/null +++ b/src/utils/self-adaption.js @@ -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 }; +} diff --git a/src/views/navigation/index.vue b/src/views/navigation/index.vue index 17f4738..c226f45 100644 --- a/src/views/navigation/index.vue +++ b/src/views/navigation/index.vue @@ -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);