UNPKG

vue-hooks-plus

Version:
26 lines (25 loc) 724 B
"use strict"; const vue = require("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 = vue.ref(getValue()); const handler = () => { value.value = getValue(); }; vue.watchEffect((onInvalidate) => { mediaQueryLists.forEach((mql) => { mql.addListener(handler); }); onInvalidate(() => { mediaQueryLists.forEach( (mql) => mql.removeListener(handler) ); }); }); return value; } module.exports = useMedia;