vue-hooks-plus
Version:
Vue hooks library
27 lines (26 loc) • 721 B
JavaScript
import { ref, watchEffect } from "vue";
function useMedia(queries, values, defaultValue) {
const mediaQueryLists = queries.map((q) => window.matchMedia(q));
const getValue = () => {
const index = mediaQueryLists.findIndex((mql) => mql.matches);
return typeof values[index] !== "undefined" ? values[index] : defaultValue;
};
const value = ref(getValue());
const handler = () => {
value.value = getValue();
};
watchEffect((onInvalidate) => {
mediaQueryLists.forEach((mql) => {
mql.addListener(handler);
});
onInvalidate(() => {
mediaQueryLists.forEach(
(mql) => mql.removeListener(handler)
);
});
});
return value;
}
export {
useMedia as default
};