Home > database >  changing a JS value according to media queries on vuejs
changing a JS value according to media queries on vuejs

Time:01-03

I have this div below that the content changes according to the variable value of 'fullSideBar', true and false. Today, this value changes with a button.

I want to know if it is possible to change the value of 'fullSideBar' when the width medias changes. Something like: @media screen and (max-width: 768px) { this.fullSideBar = false}.

This is the code:

<template>
    <div>
    <img 
        src="../../../static/icons/arrow-bar-left.svg" 
        alt="Ícone de seta a esquerda" 
         
        @click="fullSideBar = !fullSideBar"
        v-if="!this.fullSideBar"
    >
    <img 
        src="../../../static/icons/arrow-bar-right.svg" 
        alt="Ícone de seta a esquerda" 
         
        @click="fullSideBar = !fullSideBar"
        v-else
    >
    </div>
</template>
<script>
import FooterSideBarVue from './FooterSideBar.vue';
export default {
    name: 'BodyScrolling',
    components: {
        FooterSideBarVue
    },
    data (){
        return {
            footerItems: [
                'Sobre'
                , 'Documentação'
                , 'Contato'
            ],
            fullSideBar: false,
        }
    },
}
</script>

Is there any way to do that?

CodePudding user response:

You can use the window.matchMedia function to check in javascript if the window currently matches the given media query.

if (window.matchMedia("(max-width: 768px)").matches) {
   this.fullSideBar = false;
}

To react to the window size changes, use window.addEventListener("resize", myListener);:

function updateFullSideBar(evt) {
  // Check the innerWidth property or use window.matchMedia here too
  this.fullSideBar = evt.view.innerWidth < 768
}

window.addEventListener("resize", updateFullSideBar);
  • Related