Vue Component Media Queries is a lightweight library (less than 1kb gzipped) that provides Vue 2 components for integrating the `window.matchMedia` API directly into your templates and script logic. It is currently at a stable v1.0.0 release. The library differentiates itself by being highly optimized for server-side rendering (SSR), specifically tested with Nuxt.js to prevent hydration errors and support predictive rendering, making it suitable for complex responsive layouts where CSS alone might lead to performance issues or require logic. While there isn't an explicit release cadence, the library has moved from several alpha versions to a stable 1.0.0, suggesting a focus on stability for its current major version. It offers flexibility by allowing media queries to be defined globally via a `MediaQueryProvider` or used for single queries with `MatchMedia`, and can also inject query states into components.
npm install vue-component-media-queriesVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to set up global media queries using `MediaQueryProvider` and reactively consume their states within a child `MatchMedia` component. It shows a basic responsive layout changing based on mobile, tablet, or desktop viewport sizes.
For Vue 3 projects, seek an alternative `matchMedia` integration library compatible with Vue 3's composition API or consider implementing custom `matchMedia` logic.
Always evaluate if a CSS-only solution (e.g., `@media` rules) is sufficient before introducing `vue-component-media-queries`. Reserve this library for logic-dependent responsive behaviors or performance-critical conditional rendering.
Thoroughly test SSR behavior with your specific framework (e.g., Nuxt.js). Ensure `fallback` props are set appropriately to provide an initial matching state during server render, which can prevent flickering or mismatches on client-side hydration.
Always prefer installing via NPM (`npm i vue-component-media-queries`) and importing components as ES Modules. This ensures optimal bundling, tree-shaking, and dependency management for production environments.
Ensure `MatchMedia` or any component injecting `mediaQueries` is a descendant of a `MediaQueryProvider` component that has defined the necessary queries.
Set the `ssr` prop on `MediaQueryProvider` or `MatchMedia` to `true` (or a specific boolean value) and ensure `fallback` props are correctly configured to provide a default state during SSR, preventing `window.matchMedia` from being called on the server.
Import the component (`import { MediaQueryProvider } from 'vue-component-media-queries'`) and add it to your Vue component's `components` object: `components: { MediaQueryProvider }`.