Set reactive screen width with vuejs
Asked Answered
G

3

17

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
}
Grummet answered 27/7, 2018 at 20:45 Comment(1)
H
40

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!

Hyposthenia answered 27/7, 2018 at 22:32 Comment(0)
D
6

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

Dyslogistic answered 28/8, 2019 at 17:40 Comment(0)
M
3

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>
Martinsen answered 31/7, 2019 at 6:25 Comment(3)
At this point you might as well just be using media queriesStripling
@Stripling if you are wanting simple changes (e.g. display: none) then media queries are the best option. In the event it's more complex where screen resolution is important (e.g. changes of state to aria-hidden) then media queries aren't the best option. It's all based on scenario and unfortunately the OP doesn't provide that.Munos
Even in that example, [aria-hidden="true"] is a valid CSS selectorStripling

© 2022 - 2024 — McMap. All rights reserved.