A collection of utility plugins and functions when using media queries in Vue.
Contents
Use Media Query
Import and use the useMediaQuery function to evaluate a raw media query and return a boolean ref that will update with the media query.
If you wish to receive a callback of the raw media query event, provide the callback function as the second argument.
Event cleanup happens automatically when the component is unmounted, but can be manually triggered by setting the ref value to undefined.
<template>
<div>
<h3 v-if=”isHighDPI“>This must look really sharp to you!</h3>
<h3 v-else>Can you even read this?</h3>
</div>
</template>
<script setup>
import { useMediaQuery } from ‘vue-media-query’;
// Use a media query that returns a boolean ref
const isHighDPI = useMediaQuery(
`@media only screen and (-moz-min-device-pixel-ratio: 2),
only screen and (-o-min-device-pixel-ratio: 2/1),
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (min-device-pixel-ratio: 2)`,
// Optional callback with raw event
(ev) => console.log(`Callback: ${ev}`)
);
// Cleanup manually if needed
isHighDPI.value = undefined;
</script>
Use Screens
Use the useScreens function to easily create computed refs derived from custom screen size keys.
Import and use the useScreens function within parent components that will provide the $screens function to nested components. Pass a config object that maps custom screen size keys to media query values.
<div class="highlight highlight-text-html-basic notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="
<script setup>
import { useScreens } from ‘vue-media-query’;
useScreens({
sm: ‘640px’, // (min-width: 640px)
md: ‘768px’, // (min-width: 768px)
lg: ‘1024px’, // (min-width: 1024px)
xl: ‘1280px’, // (min-width: 1280px)
});
</script>”>
<!–Parent.vue–>
<script setup>
import { useScreens } from ‘vue-media-query’;
useScreens({
sm: ‘640px’, // (min-width: 640px)
md: ‘768px’, // (min-width: 768px)
lg: ‘1024px’, // (min-width: 1024px)
xl: ‘1280px’, // (min-width: 1280px)
});
</script>