MatchMedia component library for vue
npm install vue-component-media-queries
MatchMedia component library for Vue.
* 🍳 Tiny. Less than 1kb gzipped total size.
* 🌳 Tree-shakeable. Import only the necessary components right where you need them.
* 💡 Server Rendered. No hydration errors, thoroughly tested with Nuxt.js, supports predictive rendering.
* 💊 Versatile. Works both on a component level (inside ) or as an injected property (inside ).
Live playground on codesandbox
Match media queries right in your components:
``html`
`html`
There are two ways how you can use Media Queries on Web: CSS and JS runtime.
In most cases you'll be fine with just CSS, so before going any further please verify that CSS is insufficient for your case.
For example, you don't need this library if you need to toggle element visibility for non-complex elements.
You're better off using just CSS for that:
`html`You're on mobileYou're on desktop`css`
@media (min-width: 761px) {
.show-on-mobile { display: none !important; }
}
@media (max-width: 760px) {
.show-on-desktop { display: none !important; }
}
But if you encounter a significant performance degradation from rendering everything in a single pass
or have some logic bound to media queries you might want to use window.matchMedia.window.matchMedia
This library provides integration for Vue.
* Getting started
+ Installation
- NPM
- CDN
+ Usage
- Component-based (global matching)
- Component-based (single query matching)
- Provide\Inject
* API
+
- Props
* queries
* fallback
* ssr
* wrapperTag
- Events
* [change:[name]](#-change--name--)
+ query
- Props
* fallback
* ssr
* wrapperTag
* default
- Scoped Slots
* slotchange
- Events
* mediaQueries
+ injection
* SSR
+ Predictive rendering
#### NPM
1. Install library as a dependency: npm i vue-component-media-queries
1. Import components via named exports where necessary:
`js`
import { MediaQueryProvider, MatchMedia } from 'vue-component-media-queries'
#### CDN
If you don't have an option to use NPM you can use a CDN package,
it will register a global VueComponentMediaQueries variable with appropriate exports.
The CDN method is not recommended for production usage. Prefer using NPM method whenever possible.
1. Import library after Vue:
`html`
2. Get components from the global VueComponentMediaQueries object:
`html`
#### Component-based (global matching)
The primary way to use this library is to match media queries in a root wrapping component (this is your App.vue or Layout.vue),
then get the results in a child component (could be on any level in the rendering tree).
In order to do this there are two components: and .
1. does the actual matching and provides values down the render tree. You should put this component in your App.vue or Layout.vue.
2. retrieves these values from the and exposes them to rendering context through scoped slots.
You should put this component where you have to actually use these media queries.
Here's a basic setup for this method:
1. Wrap your app in a and pass queries object to it.
`html`
2. In any part of your app that's within the use component to retrieve the results of media queries.
`html`
in the example above refers to the mobile: '(max-width: 760px)' media query result taken from the .
This result is reactive – when you resize the page it will update accordingly.
----
#### Component-based (single query matching)
You can also use without .query
In that case you'll have to pass a directly to instead and get the result from a matches slot prop.
`html
`
This method should be used for one-off media queries that are not referenced anywhere else in your app and would bloat your queries object otherwise.
----
#### Provide\Inject
Lastly, it's possible to have just and no components.
Provide\Inject pattern can be used to get media queries results in your methods, computeds or lifecycle hooks.
To get the provided media queries results you'll need to:
1. Repeat the first step setting up at the start of this section
2. Inject mediaQueries in your component:
`html`
#### Props
##### queries
Type: { [name]: string }
Required: yes
queries is an object where:
* key is a media query name that would be then used in scoped slot or in mediaQueries injection.
* value is a media query expression. (How to use Media Queries)
`js`
const queries = {
mobile: '(max-width: 760px)',
tablet: '(max-width: 1024px)',
desktop: '(min-width: 1024px)',
landscape: '(orientation: landscape)'
}
queries are best passed to via the $options object$options
because contents are static and so should be your media queries object.
`html
`
##### fallback
Type: string or string[]
A key or a list of queries keys that should return true when window.matchMedia is unavailable (node.js\nuxt.js for example).
`html`
{{ mobile }}
Multiple fallbacks:
`html`
:fallback="['mobile', 'landscape']"
>
##### ssr
Type: boolean
This prop switches between eager and immediate mode for matching.
* An immediate mode sets all the queries to match before your components render.
It ensures that components using media queries won't have to re-render after a first render due to data mismatch
(all media queries return false before matching, except those listed in fallback prop).fallback
* An eager mode allows for components to render with fallback values first (passed to prop) to avoid hydration errors.
`html`
:fallback="['mobile', 'landscape']"
ssr
>
Set this prop to true if you have a custom server side rendering.true
Nuxt.js users will have this set to by default.
##### wrapperTag
Type: string
Default: span
A wrapping tag that is used when a component has more than one child.
`html`
wrapper-tag="'div'"
>
#### Events
##### change:[name]
Type: MediaQueryListEvent
Arguments:
* matches – boolean. Represents media query result.media
* — string. Media query.EventTarget
* Rest of interface.
An even fired when a media query name result changes.name is a key of queries object passed to .
`html
:queries="$options.queries"
>
`
----
#### Props
##### query
Type: string, a media query.
Required: yes, when is not a descendant of .
A media query that needs to be matched in place. See usage section for an example.
##### fallback
Type: string
Sets matches value to true when used outside of browser context (same as for ).
`html`
{{ matches }}
##### ssr
Type: boolean
Same as for .
##### wrapperTag
Type: string
Default: span
A wrapping tag that is used when a component has more than one child.
`html`
#### Scoped Slots
##### default slot
Slot props: { [name]: boolean } or { matches: boolean }
Returns a record of media queries results from the .
`html`
{{ mobile }}
Or returns a matches slot prop if you pass a query prop.
`html`
{{ matches }}
#### Events
##### change
Type: MediaQueryListEvent
Arguments:
* matches – boolean. Represents media query result.media
* — string. Media query.EventTarget
* Rest of interface.
Triggers when a result from passed media query prop changes.
`html`
----
Type: { [name]: boolean }
A record with the results of . See Provide\Inject section for an example.
You can use user agent detection (also called browser sniffing) to make a guess which media queries should return true.
This is useful when you want to avoid layout shifts and unnecessary re-renders after a hydration.
To do so, we'll have to parse user agent on server side, set fallback values for and pass them back to the client.
Here's an example of using ua-parser-js to make a guess which device is sending a request in a default Nuxt.js layout:
`html
``