0

I create a composable function to detect current screen resolution (this function works).

If I use this function in a few components, addEventListener add a new handler to the same mediaQuery. How can I manage that mediaQuery already has a listener?

import { ref } from "vue";

const breakpoints = {
  tablet: "(min-width: 769px)",
  desktop: "(min-width: 1024px)"
};

export const useBreakPoints = () => {
  let mediaQuery;
  const matches = ref({});

  const update = () => {
    for (const key in breakpoints) {
      mediaQuery = window.matchMedia(breakpoints[key]);
      matches.value = { ...matches.value, [key]: mediaQuery.matches };

      // PROBLEM IS HERE
      if (!mediaQuery.onchange) {
        mediaQuery.addEventListener("change", update);
      }
    }
  };
  update();

  return matches;
};
  • If it's supposed to be global then matches state should be global, i.e. defined outside useBreakPoint, and update needs to be called on the first useBreakPoints call only. – Estus Flask Oct 22 '22 at 21:37

0 Answers0