DEV Community

loading...

Media queries in Vuejs

dowar profile image DoWar ・2 min read

Vue has become my favorite JavaScript Framework for many reasons, but this time I am not talking about that but about an NPM package that allows you to render certain content from your template depending on the size of the screen.
As FrontEnd developers it is our duty to adapt our web applications to different screen resolutions to offer the best possible experience, that is why while I was developing a website I had the need to change some elements depending on the device with which it was being used accessing.

Requirements:

  • Vue 3
  • NPM

We execute the following command in the terminal
npm install vue3-mq

To finish its installation and configuration we will go to our main.ts file where we will import the package and add the screen resolutions, in the end it should look similar to the following:


import { createApp } from "vue";
import VueMq from "vue3-mq";

const app = createApp({});

app.use(VueMq, {
  breakpoints: {
    sm: 450,
    md: 1250,
    lg: Infinity,
  }
})

app.mount('#app');

Enter fullscreen mode Exit fullscreen mode

We will place the content between the labels
<mq-layout mq="lg"></mq-layout>
where mq is the property where we will indicate the screen resolution for that content to be displayed.

An example of use would be the following:


<mq-layout mq="lg">
  <span> Display on lg </span>
</mq-layout>
<mq-layout mq="md+">
  <span> Display on md and larger </span>
</mq-layout>
<mq-layout :mq="['sm', 'lg']" tag="span">
  Display on sm and lg
</mq-layout>

Enter fullscreen mode Exit fullscreen mode

Quite simple truth, with this we have finished and I hope that you also find it useful as it was for me, but I still cannot withdraw without first providing you with the developer repository of this NPM package https://github.com/craigrileyuk/vue3-mq.

Don't forget to program with ♥ ️.

Discussion (0)

Forem Open with the Forem app