Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set reactive screen width with vuejs

Is it possible to have a reactive window width where a variable or data property tracks a window resize

e.g

computed:{
    smallScreen(){
        if(window.innerWidth < 720){
            this.$set(this.screen_size, "width", window.innerWidth)
            return true
        }
    return false
}
like image 276
Jon Awoyele Avatar asked Jul 27 '18 20:07

Jon Awoyele


3 Answers

I don't think there's a way to do that unless you attach a listener on the window. You can add a property windowWidth on the component's data and attach the resize listener that modifies the value when the component is mounted.

Try something like this:

<template>
    <p>Resize me! Current width is: {{ windowWidth }}</p>
</template

<script>
    export default {
        data() {
            return {
                windowWidth: window.innerWidth
            }
        },
        mounted() {
            window.onresize = () => {
                this.windowWidth = window.innerWidth
            }
        }
    }
</script>

Hope that helps!

like image 92
mtflud Avatar answered Nov 20 '22 17:11

mtflud


You can also attach a class depending on the window width

<template>
    <p :class="[`${windowWidth > 769 && windowWidth <= 1024 ? 'special__class':'normal__class'}`]">Resize me! Current width is: {{ windowWidth }}</p>
</template>

<script>
export default {
    data() {
        return {
            windowWidth: window.innerWidth
        }
    },
    mounted() {
        window.onresize = () => {
            this.windowWidth = window.innerWidth
        }
    }
}
</script>

<style scoped>
.normal__class{
}
.special__class{
}
</style>
like image 21
Agani Nyakundi Avatar answered Nov 20 '22 15:11

Agani Nyakundi


If you are using multiple components with this solution, the accepted answer's resize handler function will update only the last component.

Then you should use this instead:

import { Component, Vue } from 'vue-property-decorator';

@Component
export class WidthWatcher extends Vue {
   public windowWidth: number = window.innerWidth;

   public mounted() {
       window.addEventListener('resize', this.handleResize);
   }

   public handleResize() {
       this.windowWidth = window.innerWidth;
   }

   public beforeDestroy() {
       window.removeEventListener('resize', this.handleResize);
   }
}

source: https://github.com/vuejs/vue/issues/1915#issuecomment-159334432

like image 6
aruqen Avatar answered Nov 20 '22 16:11

aruqen