UNPKG

@antdv/pro-utils

Version:

@antdv/pro-utils

41 lines (40 loc) 1.17 kB
import { ref, watchEffect } from "vue"; import { tryOnScopeDispose } from "../tryOnScopeDispose/index.mjs"; import { useSupported } from "../useSupported/index.mjs"; import { toValue } from "../utils.mjs"; function useMediaQuery(query) { const isSupported = useSupported(() => window && "matchMedia" in window && typeof window.matchMedia === "function"); let mediaQuery; const matches = ref(false); const handler = (event) => { matches.value = event.matches; }; const cleanup = () => { if (!mediaQuery) return; if ("removeEventListener" in mediaQuery) mediaQuery.removeEventListener("change", handler); else mediaQuery.removeListener(handler); }; const stopWatch = watchEffect(() => { if (!isSupported.value) return; cleanup(); mediaQuery = window.matchMedia(toValue(query)); if ("addEventListener" in mediaQuery) mediaQuery.addEventListener("change", handler); else mediaQuery.addListener(handler); matches.value = mediaQuery.matches; }); tryOnScopeDispose(() => { stopWatch(); cleanup(); mediaQuery = void 0; }); return matches; } export { useMediaQuery };