Vue 3 Breakpoints using window.matchMedia and the Composition API
npm install vue-next-breakpointsJavaScript-based Media Queries for Vue 3. Internally uses window.matchMedia and the Composition API.
NPM: npm i vue-next-breakpoints
Yarn: yarn add vue-next-breakpoints
``javascript
`
Simply pass an object with key-value pairs to useBreakpoints function, where the key is any name you want and the value is one of the following:200
- numeric value, e.g. which converts to @media screen and (max-width: 200px)80%
- string value with any units you prefer, e.g. which converts to @media screen and (max-width: 80%)[600]
- an array with one of the above values, e.g. which converts to @media screen and (min-width: 600px)[601, "1200px"]
- an array with two of the above values, e.g. which converts to @media screen and (min-width: 601px) and (max-width: 1200px)@media screen and (-webkit-min-device-pixel-ratio: 1)
- any other media query, e.g. which will not be converted in any way (@media prefix is not required, e.g. @media print is the same as just print).
Each of the specified media queries have .matches property which is either true or false. You can use them in a template or in any other method, computed property etc:
`javascript`
In most cases using .matches property will be enough, but if you want to listen for the specific breakpoint, there are two types of listeners: "enter" and "leave" and these can be assigned to any media query previously configured.
`javascript
const enterCallback = (mq) => {
console.log("Entered mobile breakpoint");
console.log("Media Query", mq);
};
const leaveCallback = (mq) => {
console.log("Left mobile breakpoint");
console.log("Media Query", mq);
};
created() {
this.breakpoints.mobile.on("enter", enterCallback);
this.breakpoints.mobile.on("leave", leaveCallback);
}
``
Event listener can be easily removed as well:javascript`
this.breakpoints.mobile.off("enter", enterCallback);
You don't have to remove those event listeners manually before the component is unmounted, it's done automatically behind the scenes.
If you don't specify the callback to remove, all listeners of the given type will be removed:
`javascript``
this.breakpoints.mobile.off("enter"); // all previously assigned listeners are gone
If you find any problems using this library or you want to propose new features to it, feel free to open an issue on Github.